Professional Documents
Culture Documents
1
Stateful Session Bean Agenda:
2
Session Beans
3
2 Types of Session Beans
4
Stateful Session Bean
5
Differences From Stateless Bean
Stateful Stateless
§ Always specific to 1 § Container may share
client stateless beans
between clients
§ Maintains client (after method
specific data completion) to
between methods optimize memory and
performance
6
Stateful Session Beans
7
Stateful Session Beans May Use
More Resources
To efficiently manage the size of its working set, a session bean container may
need to temporarily
transfer the state of an idle stateful session bean instance to some form of
secondary storage. The transfer
from the working set to secondary storage is called instance passivation. The
transfer back is called
activation. A container may only passivate a session bean instance when the
instance is not in a transaction.
8
When to Use Stateful Session EJBs?
9
Implementing a Session Bean
10
Example Scenario: Use Cases
customer
add/remove item to/from shopping cart
11
Example: Shopping Cart Class
State:
Client
ShoppingCart Specific
Instance
variable
Hashtable cartItems
addItem()
removeItem()
getItems()
12
Example Scenario: Sequence
Diagram
Shopping
: Customer
Cart
addItem()
removeItem()
getItems()
13
Example Continued
CartHome
Cart
client bean
Cart
14
Session Bean Implementation
15
EJB™ API Review
<<Interface>> <<Interface>>
java.RMI.Remote java.io.serializable JDK
<<Interface>>
EnterpriseBean
<<Interface>> <<Interface>>
EJBHome EJBObject javax.ejb
<<Interface>>
SessionBean
Container
xxxCart xxxCart xxx provider
EJBHome EJBObject CartBean
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
16
Session Context Interface
<<Interface>>
EJBContext
getEJBHome()
getEnvironment()
getCallerIdentity()
isCallerInRole()
getUserTransaction()
setRollBackOnly()
<<Interface>>
SessionContext
getEJBObject()
17
javax.EJB™ Session Bean
Interface
<<Interface>>
java.io.serializable
<<Interface>>
EnterpriseBean
<<Interface>>
SessionBean
setSessionContext()
ejbRemove()
ejbActivate()
ejbPassivate()
18
Session Bean Implementation
• Define the session Bean’s remote interface (Cart). 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.
19
1) Create the Remote Interface
<<Interface>>
EJBObject extends
<<Interface>>
ShoppingCart
addItem()
removeItem()
getItems()
}
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
20
Session Bean Implementation
• Define a home interface (CartHome) 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.
21
2) Create the Home Interface
<<Interface>>
EJBHome
<<Interface>>
ShoppingCartHome
Creating a session object: The home interface defines one or more create(...)
methods, one for each way to create a session object. The arguments of the
create methods are typically used to initialize the state of the created session
object.
The following are the requirements for the session bean’s home interface:
• 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 bean’s home interface must define one or more create(...) methods.
•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.)
• The return type for a create method must be the session bean’s 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.
22
Session Bean Implementation
• Write the business logic in the session Bean class (CartBean). The enterprise
Bean must implement the javax.ejb.SessionBean interface, and define the
ejbCreate(...) methods invoked at an EJB™ object creation.
23
3) ShoppingCartBean Implementation
<<Interface>>
SessionBean
implements
setSessionContext()
ejbRemove()
ejbActivate()
ejbPassivate()
<<Interface>> ShoppingCartBean
ShoppingCart
addItem() addItem()
removeItem() removeItem()
getItems() getItems()
must match ejbCreate()
for container setSessionContext()
“glue” ejbRemove()
<<Interface>>
ejbActivate()
ShoppingCartHome
ejbPassivate()
create()
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.
24
Lifecycle of a Stateful Session
Bean (Without Transactions)
does not
exist
1) newInstance()
2) setSessioncontext() ejbRemove()
3)ejbCreate()
ejbPassivate()
method-ready
EJB passive
Instance
25
3) ShoppingCartBean: Implement Shopping
Cart Interface Business Methods
26
Creating a Stateful Session
Session bean
client EJBHome EJBObject instance
context
create()
new
new
new
setSessionContext()
ejbCreate(args)
The container creates an instance of a session bean in three steps. First, the
container calls the bean class’ newInstance method to create a new session
bean instance. Second, the container calls the setSessionContext method to
pass the context object to the instance. Third, the container calls the instance’s
ejbCreate method whose signature matches the signature of the create method
invoked by the client.
27
3) ShoppingCartBean: Implement Home
Interface Create Method
//implement ShoppingCartHome interface
create
28
Passivation and Activation of a
Stateful Session Object
EJB EJB Cont- Session bean secondary
client instance store
Home Object ainer context
ejbPassivate()
Passivation
write state
read state
Activation
ejbActvate()
The container’s caching algorithm may decide that the bean instance should be
evicted from memory (this could be done at the end of each method, or by
using an LRU policy). The container issues ejbPassivate on the instance. After
this completes, the container saves the instance’s state to secondary storage. A
session bean can be passivated only between transactions, and not within a
transaction.
29
3) ShoppingCartBean: Implement Session
Interface Container Callback Methods
30
Removal of a Stateful Session
Object
bean
client EJBHome EJBObject context instance
remove()
ejbRemove()
When the client calls remove on the home or remote interface to remove the
session object, the container issues ejbRemove() on the bean instance. This
ends the life of the session bean instance and the associated session object.
31
3) ShoppingCartBean: Implement Session
Interface Container Callback Methods
32
Lifecycle of a Stateful Session
Bean (Without Transactions)
does not
exist
1) newInstance()
2) setSessioncontext() ejbRemove()
3)ejbCreate()
ejbPassivate()
method-ready
EJB passive
Instance
33
Exceptions
• System Exception
– indicates a problem with the services that
support an application.
• Examples: a database connection cannot be
obtained, a SQL insert fails because the
database is full. If enterprise bean
encounters a sytem-level problem, it throws a
javax.ejb.EJBException.
• Application Exception
– signals an error in the business logic of an
enterprise bean. 2 kinds:
• Customized: InsufficentBalanceException
• predefined: CreateException
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
Handling Exceptions
The exceptions thrown by enterprise beans fall into two categories: system and
application. A system exception indicates a problem with the services that
support an application. Examples of these problems include the following: a
database connection cannot be obtained, a SQL insert fails because the
database is full, a lookup method cannot find the desired object. If your
enterprise bean encounters a sytem-level problem, it should throw a
javax.ejb.EJBException. The container will wrap the EJBException in a
RemoteException, which it passes back to the client. Because the
EJBException is a subclass of the RuntimeException, you do not have to
specify it in the throws clause of the method declaration. If a system exception
is thrown, the EJB container might destroy the bean instance. Therefore, a
system exception cannot be handled by the bean's client program; it requires
intervention by a system administrator.
An application exception signals an error in the business logic of an enterprise
bean. There are two types of application exceptions: customized and
predefined. A customized exception is one that you've coded yourself, such as
the InsufficentBalanceException thrown by the debit business method of the
AccountEJB example. The javax.ejb package includes several predefined
exceptions that are designed to handle common problems. For example, an
ejbCreate method should throw a CreateException to indicate an invalid input
parameter. When an enterprise bean throws an application exception, the
container does not wrap it in another exception. The client should be able to
handle any application exception it receives.
If a system exception occurs within a transaction, the EJB container rolls back 34
the transaction. However, if an application exception is thrown within a
Exceptions
Handling Exceptions
The exceptions thrown by enterprise beans fall into two categories: system and
application. A system exception indicates a problem with the services that
support an application. Examples of these problems include the following: a
database connection cannot be obtained, a SQL insert fails because the
database is full, a lookup method cannot find the desired object. If your
enterprise bean encounters a sytem-level problem, it should throw a
javax.ejb.EJBException. The container will wrap the EJBException in a
RemoteException, which it passes back to the client. Because the
EJBException is a subclass of the RuntimeException, you do not have to
specify it in the throws clause of the method declaration. If a system exception
is thrown, the EJB container might destroy the bean instance. Therefore, a
system exception cannot be handled by the bean's client program; it requires
intervention by a system administrator.
An application exception signals an error in the business logic of an enterprise
bean. There are two types of application exceptions: customized and
predefined. A customized exception is one that you've coded yourself, such as
the InsufficentBalanceException thrown by the debit business method of the
AccountEJB example. The javax.ejb package includes several predefined
exceptions that are designed to handle common problems. For example, an
ejbCreate method should throw a CreateException to indicate an invalid input
parameter. When an enterprise bean throws an application exception, the
container does not wrap it in another exception. The client should be able to
handle any application exception it receives.
If a system exception occurs within a transaction, the EJB container rolls back 35
the transaction. However, if an application exception is thrown within a
Session Bean Implementation
36
4) Compile the Remote & Home Interfaces and
Implementation Class.
37
Session Bean Implementation
38
5) Create Deployment Descriptor
deploytool
Set the values for the class names, transaction
attributes,
Environment values, resource references…
39
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
40
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
41
5) Create Deployment Descriptor
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems Inc.//DTD
Enterprise JavaBeans 1.2//EN' 'http://java.sun.com/j2ee/dtds/ejb-
jar_1_2.dtd'>
<ejb-jar>
<description>no description</description>
<display-name>CartEjb</display-name>
<enterprise-beans>
<session>
<description>no description</description>
<display-name>CartBean</display-name>
<ejb-name>CartBean</ejb-name>
<home>CartHome</home>
<remote>Cart</remote>
<ejb-class>CartEJB</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
42
5) Create DD Cont.
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>CartBean</ejb-name>
<method-intf>Remote</method-intf>
<method-name>removeBook</method-name>
<method-param>java.lang.String</method-param>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
43
Session Bean Implementation
44
6) Package in an ejb-jar File.
Cart
CartHome
CartEJB
Interfaces bean
XML DD
Deployment
Descriptor
45
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
46
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
47
Session Bean Implementation
48
7) Deploy the Enterprise
Application
ejb-jar(s), web jars Application jar: CartHome
Cart interfaces, CartEJB™ beans
JSP beans, servlets
Deployment tool
Deployment tool
The tools provided by xxx container provider are responsible for the
following:
• Generate the class (xxxRemoteCart) that implements the session bean’s
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 (xxxxCartBean).
xxxxCartBean includes the business logic from the CartBean class mixed with
the services defined in the xxxxBean class. Acme tools can use inheritance,
delegation, and code generation to achieve a mix-in of the two classes.
• Generate the class (xxxxCartHome) that implements the session bean’s home
interface. The tools also generate the classes that implement the
communication protocol specific artifacts for the home interface.
• Generate the class (xxxxCartMetaData) that implements the
javax.ejb.EJBMetaData interface for the Cart Bean. Many of the above classes
and tools are container-specific (i.e., they reflect the way xxxx Corp
implemented them). Other container providers may use different mechanisms
to produce their runtime classes, and these classes will likely be different from
those generated by xxx’s tools.
49
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
50
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
51
Create a Client
52
Cart Client Code
53
Exercise: Implement Duke’s Bookstore
ShoppingCart Stateful Session Bean
customer
Remove/add Item from/to cart
customer
Get Items in cart…
54
ShoppingCartEJB
<<Interface>>
ShoppingCartItem
ShoppingCart
product
ShoppingCartEJB price
addItem ()
cart quantity
deleteItem()
numberOfItems
clear() getProduct()
getItems() getQuantity()
getItem() addItem () getPrice()
getNumberOfItems() deleteItem()
getTotal()
clear()
getItems()
getItem()
getNumberOfItems()
getTotal()
ejbCreate()
setSessionContext() Receipt
ejbRemove() description
ejbActivate() customerId
ejbPassivate() orderId
date
< < Interface>>
ShoppingCartHome price
create()
55