Professional Documents
Culture Documents
Developing A Stateless Session Enterprise Java Bean
Developing A Stateless Session Enterprise Java Bean
What is a stateless session bean When to use session beans Steps for implementing a stateless session bean Overview of EJB APIs Example Stateless session bean implementation Assembling an deploying the example session bean Writing and running the client of the example session bean
Copyright 2000 Sun Microsystems, Inc., All rights reserved.
Entity Bean
Entity Bean
entity
entity
entity
A session bean is implemented to perform a sequence of tasks within the context of a transaction. For example, a session bean can execute a process or a transaction that accesses a database to display certain information to the client.
3 major design patterns for distributed objects multi-tier systems: EJB stateless session bean: stateless server object: object which provides responses to requests without storing information between requests (like http). Can be re-used on different client after method call finished. EJB stateful session bean: session oriented object: session is acting as agent for the client, keeping state information until session is finished , 1 per client until session is finished. EJB entity bean: persistent object: wraps "object data" stored in a database and provides operations to manipulate this data. shared among multiple clients concurrently.
Stateless session beans model business processes that can be completed in a one method call. Stateless session beans do not maintain their state across method calls. Typically, you use stateless beans when the entire task can be performed within a single method call. Any instance of a stateless session bean can be used at any time by any client.
o Do not retain client information from one method invocation to the next. o Client passes any needed information as parameters to the business methods. oUsed mainly to provide a pool of beans to handle frequent but brief requests. oThe EJB server transparently reuses instances of the bean to service different clients.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.
Stateless Session Beans Stateless session beans are designed strictly to provide server-side behavior. They are anonymous in that they contain no user-specific data. In fact, the EJB architecture provides ways for a single stateless session bean to serve the needs of many clients. This means that all stateless session bean instances are equivalent when they are not involved in serving a client-invoked method. The term stateless means that it does not have any state information for a specific client. However, stateless session beans can have non-client specific state, for example, an open database connection. A stateless session Bean maintains no state across methods and transactions -the EJB server transparently reuses instances of the Bean to service different clients at the per-method level (access to the session bean is serialized and is 1 client per session bean per method. -Pool of session beans < # clients because they can be reused
Stateless vs Stateful
Cart items
oBut may require the client to maintain state information on the client side which can mean more complex client code.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.
o Can be recycled. o Number of instances to create is minimized. o Shorter life (no client session) optimizes resource usage. o Improved performance due to fewer connections across the network.
Note: The difference in use of resources for stateless and stateful is application server specific.
10
5.4.2.1 Uses of Stateless Session Beans A Bean Provider can use the following session bean characteristics as guidelines when deciding whether to model a business object as a stateless session bean: Modeling reusable service objects A business object that provides some generic service to all its clients can be modeled as stateless session beans. Such an object does not need to maintain any client specific state information, so the same bean instance can be reused to service other clients. For example, it would be appropriate to model a business object that validates an employee ID against a database as a state-less service. Providing high performance A stateless session bean can be very efficient as it requires fewer system resources by the virtue of being not tied to one client. Since stateless session beans minimize the resources needed to support a large number of clients, depending on the implementation of the EJB server, applications that use this approach may scale better than those using stateful session beans. However, this benefit may be offset by the increased complexity of the client application that uses the stateless session beans because the client has to perform the state management functions. Operating on multiple rows at a time A business object that manipulates multiple rows in a database and represents a shared view of the data is an ideal stateless session bean. An example of a such business object would be a catalog object that presents a list of various products and categories. Since all users would be interested in such information, the stateless session bean that represents it could easily be shared. Providing procedural view of data In a procedural view of data, methods of the business object do not operate on instance variables. Instead they behave like calls in a procedural language. The method caller provides all the input and the method returns all output to the caller. If a business object exhibits such functionality then it should be modeled as a stateless session bean. Example: A Catalog Bean The sample application uses a stateless session beans to model a catalog object. A catalog object provides browsing and searching services to its clients. Both of the primary functions of the catalog, browsing and searching, are generic services that are not tied to any particular client. Also, the catalog object operates on multiple rows in the database at the same time and provides a shared view of the data.
11
12
Transfer Money
Customer
Use Case: ATM customer transfers money from checking to savings account
13
ATM
0* 0*
Account
balance
transfer()
accesses
withdraw() deposit()
Checking Account
Savings Account
14
: Customer
1: transfer() 2: debit()
3: credit())
15
Transfer
16
What the ATM session Bean provider is responsible for: Define the session Beans remote interface (Atm). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for a RMI-IIOP remote interface. The remote interface must be defined as public. Write the business logic in the session Bean class (AtmBean). The enterprise Bean must implement the javax.ejb.SessionBean interface, and define the ejbCreate(...) methods invoked at an EJB object creation. Define a home interface (AtmHome) for the enterprise Bean. The home interface must be defined as public, extend the javax.ejb.EJBHome interface, and follow the standard rules for RMI-IIOP remote interfaces. Define a deployment descriptor specifying any declarative metadata that the session Bean provider wishes to pass with the Bean to the next stage of the development/deployment work-flow.
17
JDK
javax.ejb
<<Interface>> AtmHome
<<Interface>> Atm
AtmBean
xxxatm EJBHome
xxxatm EJBObject
xxx AtmBean
The tools provided by xxx Corporation are responsible for the following: Generate the class (xxxRemoteAtm) that implements the session beans remote interface. The tools also generate the classes that implement the communication protocol specific artifacts for the remote interface. Generate the implementation of the session Bean class suitable for the xxx container (xxxAtmBean). xxxAtmBean includes the business logic from the AtmBean class mixed with the services defined in the xxxBean class. xxx tools can use inheritance, delegation, and code generation to achieve a mix-in of the two classes. Generate the class (xxxAtmHome) that implements the session beans home interface. Generate the class (xxxAtmMetaData) that implements the javax.ejb.EJBMetaData interface for the Atm Bean.
18
<<Interface>> EJBHome
<<Interface>> EJBObject
The EJBHome interface is extended by all enterprise Bean's home interfaces. An enterprise Bean's home interface defines the methods that allow a client to create, find, and remove EJB objects. Each enterprise Bean has a home interface. The home interface must extend the javax.ejb.EJBHome interface, and define the enterprise Bean type specific create and finder methods (session Beans do not have finders). The home interface is defined by the enterprise Bean provider and implemented by the enterprise Bean container. Method Summary: EJBMetaData getEJBMetaData() Obtain the EJBMetaData interface for the enterprise Bean. HomeHandle getHomeHandle() Obtain a handle for the home object. Void remove(Handle handle) Remove an EJB object identified by its handle. Void remove(java.lang.Object primaryKey) Remove an EJB object identified by its primary key. The EJBObject interface is extended by all enterprise Bean's remote interface. An enterprise Bean's remote interface provides the client's view of an EJB object. An enterprise Bean's remote interface defines the business methods callable by a client. Each enterprise Bean has a remote interface. The remote interface must extend the javax.ejb.EJBObject interface, and define the enterprise Bean specific business methods. The enterprise Bean's remote interface is defined by the enterprise Bean provider and implemented by the enterprise Bean container. Method Summary EJBHome getEJBHome() Obtain the enterprise Bean's home interface. Handle getHandle() Obtain a handle for the EJB object. java.lang.Object getPrimaryKey() Obtain the primary key of the EJB object. Boolean isIdentical(EJBObject obj) Test if a given EJB object is identical to the invoked EJB object. void remove() Remove the EJB object.
19
<<Interface>> EnterpriseBean
<<Interface>> SessionBean
<<Interface>> EntityBean
The EnterpriseBean interface must be implemented by every enterprise Bean class. It is a common super interface for the SessionBean and EntityBean interfaces. The SessionBean interface is implemented by every session enterprise Bean class. The container uses the SessionBean methods to notify the enterprise Bean instances of the instance's life cycle events. Method Summary: void ejbActivate() The activate method is called when the instance is activated from its "passive" state. void ejbPassivate() The passivate method is called before the instance enters the "passive" state. void ejbRemove() A container invokes this method before it ends the life of the session object. void setSessionContext(SessionContext ctx) Set the associated session context.
20
<<Interface>> SessionContext
<<Interface>> EntityContext
getEJBObject()
getEJBObject() getPrimaryKey()
The SessionContext interface A container provides the session bean instances with a SessionContext, which gives the session bean instance access to the instances context maintained by the container. This give information about the beans home object, current transaction information, security role information. The SessionContext interface has the following methods: The getEJBObject method returns the session beans remote interface. The getEJBHome method returns the session beans home interface. The getCallerPrincipal method returns the java.security.Principal that identifies the invoker of the bean instances EJB object. The isCallerInRole method tests if the session bean instances caller has a particular role. The setRollbackOnly method allows the instance to mark the current transaction such that the only outcome of the transaction is a rollback. Only instances of a session bean with container-managed transaction demarcation can use this method. The getRollbackOnly method allows the instance to test if the current transaction has been marked for rollback. Only instances of a session bean with container-managed transaction demarcation can use this method. The getUserTransaction method returns the javax.transaction.UserTransaction interface. The instance can use this interface to demarcate transactions and to obtain transaction status. Only instances of a session bean with bean-managed transaction demarcation can use this method.
21
Implements SessionBean interface Does not use primary key object Uses create method to create instance, stateful to initialize local data
Session EJB objects are created, associated with a specific client, and then removed as needed, whereas entity EJB objects represent permanent data in a data storage that can be uniquely identified with a primary key. Because the instance data for session beans is not persistent, the session bean class does not have callback methods for storing data to and loading data from a data source.
22
What the ATM session Bean provider is responsible for: Define the session Beans remote interface (Atm). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for a RMI-IIOP remote interface. The remote interface must be defined as public.
23
Session beans remote interface The following are the requirements for the session beans remote interface: The interface must extend the javax.ejb.EJBObject interface. The methods defined in this interface must follow the rules for RMI/IIOP. This means that their arguments and return values must be of valid types for RMI/IIOP, and their throws clause must include the java.rmi.RemoteException. The remote interface is allowed to have super interfaces. Use of interface inheritance is subject to the RMI/IIOP rules for the definition of remote interfaces. For each method defined in the remote interface, there must be a matching method in the session beans class. The matching method must have: The same name. The same number and types of arguments, and the same return type. All the exceptions defined in the throws clause of the matching method of the session bean class must be defined in the throws clause of the method of the remote interface.
24
What the ATM session Bean provider is responsible for: Define a home interface (AtmHome) for the enterprise Bean. The home interface must be defined as public, extend the javax.ejb.EJBHome interface, and follow the standard rules for RMI-IIOP remote interfaces.
25
<<Interface>> AtmHome
create()
Session beans home interface requirements: The interface must extend the javax.ejb.EJBHome interface. The methods defined in this interface must follow the rules for RMI/IIOP. This means that their arguments and return values must be of valid types for RMI/IIOP, and that their throws clause must include the java.rmi.RemoteException. The home interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI/IIOP rules for the definition of remote interfaces. A session beans home interface must define one or more create(...) methods. (stateless only 1) Each create method must be named create, and it must match one of the ejbCreate methods defined in the session bean class. The matching ejbCreate method must have the same number and types of arguments. (Note that the return type is different.) (stateless no arguments) The return type for a create method must be the session beans remote interface type. All the exceptions defined in the throws clause of an ejbCreate method of the session bean class must be defined in the throws clause of the matching create method of the home interface. The throws clause must include javax.ejb.CreateException.
26
What the ATM session Bean provider is responsible for: Write the business logic in the session Bean class (AtmBean). The enterprise Bean must implement the javax.ejb.SessionBean interface, and define the ejbCreate(...) methods invoked at an EJB object creation.
27
3) AtmBean Implementation
<<Interface>> SessionBean implements
setSessionContext() ejbRemove() ejbActivate() ejbPassivate() <<Interface>> Atm transfer() must match for container glue <<Interface>> AtmHome create()
AtmBean
The following are the requirements for the session bean class: must implement the javax.ejb.SessionBean interface. must be defined as public, must not be final, and must not be abstract. must have a public constructor that takes no parameters. The Container uses this constructor to create instances of the session bean class. must not define the finalize() method. must implement the business methods and the ejbCreate methods. If the class is a stateful session bean, it may optionally implement the javax.ejb.SessionSynchronization interface. The session bean class may have superclasses and/or superinterfaces. If the session bean has superclasses, then the business methods, the ejbCreate methods, the methods of the SessionBean interface, and the methods of the optional SessionSynchronization interface may be defined in the session bean class, or in any of its superclasses. The session bean class is allowed to implement other methods (for example helper methods invoked internally by the business methods) in addition to the methods required by the EJB specification.
28
1) newInstance()
ejbRemove()
2) setSessioncontext() 3)ejbCreate()
method-ready pool
EJB Instance
business method
29
data base
business method business method read, update data register resource mgr
30
Bean business-logic methods: These methods must match the methods defined in this EJB's remote interface, Atm. Although AtmBean does not implement the Atm interface, generated stub classes on the client side will. Calls on those classes will be forwarded to the AtmBean. Business methods The session bean class may define zero or more business methods whose signatures must follow these rules: The method names can be arbitrary, but they must not start with ejb to avoid conflicts with the callback methods used by the EJB architecture. The business method must be declared as public. The method must not be declared as final or static. The arguments and return value types for a method must be legal types for RMI/IIOP. The throws clause may define arbitrary application exceptions. Compatibility Note: EJB 1.0 allowed the business methods to throw the java.rmi.RemoteException to indicate a non-application exception. This practice is deprecated in EJB 1.1an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another RuntimeException to indicate non-application exceptions to the Container
31
create() new
32
container
session context
synchronization
bean instance
trans action
data base
new
33
} EXAMPLE DEPLOYMENT DESCRIPTOR XML FOR EJB REFERENCE <ejb-ref> <ejb-ref-name>ejb/Account</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <home>package.AccountHome</home> <remote>package.Account</remote> </ejb-ref>
Copyright 2000 Sun Microsystems, Inc., All rights reserved.
java.lang.Object objref = ic.lookup("java:comp/env/ejb/Account"); accountHome=(AccountHome)PortableRemoteObject.narrow(objref, AccountHome.class); } catch (NamingException ne) { System.err.println("ejbCreate: Caught unexpected NamingException:"); }
Bean create methods must match the methods defined in this EJB's home interface, AtmHome. Container tools generate the implementation of the AtmHome class and the client stub and server skeleton classes. Calls on those classes will be forwarded to the AtmBean. A stateless session bean must have only one ejbCreate method, which must return void and contain no arguments. In a stateless session bean, none of the methods depend on the values of variables set by any other method, except for the ejbCreate, setSessionContext methods which set the initial (identical) state of each bean instance. The term stateless signifies that an instance has no state for a specific client. However, the instance variables of the stateless session bean can contain non-client specific state across client-invoked method calls. Examples of such states include an open database connection or an object reference to an EJB object. ejbCreate method The stateless session bean class must define one ejbCreate(...) methods whose signature must follow these rules: The method name must be ejbCreate. The method must be declared as public. The method must not be declared as final or static. The return type must be void. The methods arguments must be legal types for RMI/IIOP. The throws clause may define arbitrary application exceptions, possibly including the javax.ejb.CreateException.
34
container
session context
synchronization
bean instance
trans action
data base
ejbRemove()
35
remove()
36
// Stateless Session Beans are not activated/passivated // so these methods are always empty
Bean callback methods: The container uses these to alert the bean of runtime events. Each method is called at a specific time during the life cycle of a bean. The beans container calls the setSessionContext method to associate a session bean instance with its context maintained by the container. Typically, a session bean instance retains its session context as part of its conversational state. The ejbRemove notification signals that the instance is in the process of being removed by the container. In the ejbRemove method, the instance typically releases the resources that it allocated in the ejbCreate method. ejbActivate/ejbPassivate: All Stateless Session bean instances are equivalent when they are not involved in serving a client-invoked method. A container only needs to retain the number of instances required to service the current client load. Due to client think time, this number is typically much smaller than the number of active clients. Passivation is not needed for stateless sessions. The container creates another stateless session bean instance if one is needed to handle an increase in client work load. If a stateless session bean is not needed to handle the current client work load, the container can destroy it.
37
1) newInstance()
ejbRemove()
2) setSessioncontext() 3)ejbCreate()
method-ready pool
EJB Instance
business method
38
39
40
What the ATM session Bean provider is responsible for: Define the session Beans remote interface (Atm). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for a RMI-IIOP remote interface. The remote interface must be defined as public. Write the business logic in the session Bean class (AtmBean). The enterprise Bean must implement the javax.ejb.SessionBean interface, and define the ejbCreate(...) methods invoked at an EJB object creation. Define a home interface (AtmHome) for the enterprise Bean. The home interface must be defined as public, extend the javax.ejb.EJBHome interface, and follow the standard rules for RMI-IIOP remote interfaces. Define a deployment descriptor specifying any declarative metadata that the session Bean provider wishes to pass with the Bean to the next stage of the development/deployment work-flow.
41
<!DOCTYPE order SYSTEM "order.dtd"> Document Type Definition(DTD) <order id="A002"> <book isbn="0-201-34285-5"> <title>The XML Companion</title> <author>Neil Bradley</author> <publisher>Addison-Wesley</publisher> </book> </order> Element Attribute
42
<assembly-descriptor> . . . </assembly-descriptor>
</ejb-jar>
Assembly data
The role of the deployment descriptor is to capture the declarative information (i.e information that is not included directly in the enterprise beans code) that is intended for the consumer of the ejb-jar file. There are two basic kinds of information in the deployment descriptor: Enterprise beans structural information. Structural information describes the structure of an enterprise bean and declares an enterprise beans external dependencies. Providing structural information in the deployment descriptor is mandatory for the ejb-jar file producer. The structural information cannot, in general, be changed because doing so could break the enterprise beans function. Application assembly information. Application assembly information describes how the enterprise bean (or beans) in the ejb-jar file is composed into a larger application deployment unit. Providing assembly information in the deployment descriptor is optional for the ejb-jar file producer. Assembly level information can be changed without breaking the enterprise beans function, although doing so may alter the behavior of an assembled application.
43
Set the values for the class names, transaction attributes, Environment values,resource references, EJB references
44
This example sets the EJB reference for referencing the Account Bean. Example code in the AtmEJB for referencing the Account Bean: Context ic = new InitialContext(); java.lang.Object objref = ic.lookup("java:comp/env/ejb/Account"); accountHome=(AccountHome)PortableRemoteObject.narrow(objref, AccountHome.class);
45
This example show setting the transaction attributes. We will go over transactions in Lecture 4. Here we set the method transfer to transaction required because we want to make sure that the transfer takes place in a transaction, so that either both the credit and debit accounts are updated or NO accounts are updated.
46
47
5) Create DD Cont.
</enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>AtmBean</ejb-name> <method-intf>Remote</method-intf> <method-name>transfer</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar>
48
49
AtmEJB bean
XML DD
Deployment Descriptor
50
51
52
53
Deployment tool
Server Jar: Atm and Account EJBHome EJBObject Stubs and Object implementations Enterprise Beans
J2EE Reference Implementation Deployment: Behind the Scenes 1. 2. The J2EE process opens the application JAR file, reads the deployment descriptors, and generates the home interface and EJBObject implementation for each Bean. The J2EE process compiles the home interface and the EJBObject implementations and then runs the rmic command on the class files. This step creates the stubs and skeletons for the home and remote objects. The server packages the generated classes into a server JAR file and stores the JAR file in the repository. The server creates a client JAR file that contains the home and remote interfaces and the stubs for the home and remote objects. The server sends the client JAR file to the deployer and saves the file according to the name chosen at the start of the deployment process. The location of the client JAR file must be added to the CLASSPATH environment variable on any client that calls the application. Then, at runtime, the appropriate stub classes can be loaded so that the client can successfully locate objects, for example, the home object for an enterprise bean in the application. The J2EE server starts a process which loads the server JAR file and creates containers for the enterprise beans and binds the beans to the JNDI names in the name server. At this point, the deployment process is complete.
3. 4.
5.
6. 7.
54
Example of Deployment of Bank Application .ear consisting of Atm Session EJB .jar and Account Entity EJB .jar.
55
Create a Client
1. Use JNDI to lookup EJBs home interface. 2. Call homes create method to get the EJB remote object interface. 3. Call beans business methods thru remote interface.
56
1) Use JNDI name services to locate a name server: Create an InitialContext (starting point) with server environment properties. 2)lookup the Atm EJBHome interface using the JNDI name given in deployment descriptor -lookup returns a stub reference to the object implementation of AccountHome 3)call create to get a reference to the Atm EJBObject stub. 4)call Atm business methods
57
find
Account Bean
transfer
find
EJBObject EJBObject
Client
Atm Bean
withdraw
deposit
EJBObject
Account Bean
server
Example of Sequence of events for Client calling the Transfer method on the Atm remote interface stub.
58
customer
customer
customer
1)Customer finds book by ISBN 2)Customer searches for books by subject, author title.
59
A Catalog object represents different products and provides browsing and searching services to its clients. Both of the primary functions of the catalog, browsing and searching, are generic services which are not tied to any particular client. Also, the catalog object reads multiple rows in the database at the same time and provides a shared view of the data.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.
60
CatalogEJB
<<Interface>> Catalog getBooks() getBookDetails() findBooksBySubject()
BookDetails
CatalogEJB
getBooks() getBookDetails() findBooksBySubject() ejbCreate() setSessionContext() ejbRemove() ejbActivate() ejbPassivate()
ISBN title author publisher subject description price getISBN() getTitle() getAuthor() getPrice() getDescription() getPublisher()
61