You are on page 1of 55

Developing a Stateful Session

Enterprise Java Bean

1
Stateful Session Bean Agenda:

How to develop and deploy a stateful


session bean by example:
§ What is a stateful session bean
§ When to use stateless vs. stateful
§ Steps for implementing a stateful session bean
§ Overview of session EJB™ APIs
§ Example Stateful 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.

2
Session Beans

Represents Business Process


§Atransient agent for an individual client that
executes on a server (e.g., ShoppingCart)
§Session beans are often a client of multiple entity
beans
§Implements javax.ejb.SessionBean interface

§State management types for session EJBs


§stateful- session bean may maintain state
information across method calls
§stateless - session bean may be re-used to service
multiple clients

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

3
2 Types of Session Beans

§ Stateless: execute a request and return


a result without saving any state
information.
§ Stateful: performs tasks for client and
maintains state on behalf of client.

State instance data

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A stateful session bean maintains “conversational state” or instance data


pertaining to 1 client between method calls.
Each stateful session bean is associated with a particular client. It is not
designed to be persistent. It maintains data that is transitional and relevant only
for a particular session with a specific client. A stateful session bean instance
typically cannot survive system failures and other destructive events.

4
Stateful Session Bean

§ Client session oriented.


§ Acts as agent for the client, storing
state information in instance variables
until session is finished.
§ 1 per client, associated with client until
removed.

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

•A stateful session bean holds the client session’s state.


•A stateful session bean is an extension of the client that creates it.
•Its fields contain a conversational state on behalf of the session object’s client. This state
describes the conversation represented by a specific client/session object pair.
•It can read and update data in a database on behalf of the client. Within a transaction, some of
this data may be cached in the instance.
• Its lifetime is controlled by the client.
A session object’s conversational state is usually not written to the database. A session bean
developer stores it in the session bean instance’s fields and assumes its value is retained for the
lifetime of the instance.
On the other hand, the session bean must explicitly manage cached database data. A session
bean instance must write any cached database updates prior to a transaction completion, and it
must refresh its copy of any potentially stale database data at the beginning of the next
transaction.
The goal of the session bean model is to make developing a session bean as simple as
developing the same functionality directly in a client. The container manages the life cycle of
the session bean instances. It notifies the instances when bean action may be necessary, and it
provides a full range of services to ensure that the session bean implementation is scalable and
can support a large number of clients.

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

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

6
Stateful Session Beans

§ Store client specific properties as instance


variables.
§ Expose methods to manipulate properties
(variables).
§ Intended for longer-duration services,
where it is necessary to maintain instance
variables or transactional state between
methods.

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Stateful session Beans maintain conversational state across methods and


transactions
-as a result, the EJB™ server binds the the Enterprise Bean instances to clients
directly.

7
Stateful Session Beans May Use
More Resources

1 Stateful Session Bean per Client:


§ Components have longer life (require
resources).
§ Cannot be shared between clients.
§ More instances may be created.
§ 1 session per client may use more
connections than stateless.
But application servers can “swap out”
activate/passivate beans to efficiently
manage resources.

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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?

A business object should be modeled as a


stateful session bean if it is:
• Client specific
• The bean's state must be initialized from input
parameters when it is created.
• The bean needs to hold information about the
client across method invocations.
• Non persistent
• Short lived (life of client session)
• Not shared among multiple clients
• Spanning multiple business concepts (not just
request response service)

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

9
Implementing a Session Bean

• A typical example of a Stateful session


bean is an online shopping cart. We will
use this example to show how to
implement a Stateful session bean.

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

10
Example Scenario: Use Cases

customer
add/remove item to/from shopping cart

customer get items in shopping cart

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

11
Example: Shopping Cart Class

State:
Client
ShoppingCart Specific
Instance
variable
Hashtable cartItems

addItem()
removeItem()
getItems()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

12
Example Scenario: Sequence
Diagram

Shopping
: Customer
Cart

addItem()

removeItem()

getItems()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

13
Example Continued

CartHome
Cart
client bean
Cart

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

14
Session Bean Implementation

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the
session bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

What the session Bean provider is responsible for


• 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.
• 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.
• 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.
• 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 workflow.

15
EJB™ API Review

<<Interface>> <<Interface>>
java.RMI.Remote java.io.serializable JDK

<<Interface>>
EnterpriseBean
<<Interface>> <<Interface>>
EJBHome EJBObject javax.ejb
<<Interface>>
SessionBean

<<Interface>> <<Interface>> Bean


CartBean
CartHome Cart provider

Container
xxxCart xxxCart xxx provider
EJBHome EJBObject CartBean
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

What the container provider is responsible for


The tools provided by xxxx Corporation 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 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 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. Tools can use
inheritance, delegation, and code generation to achieve a mix-in of the two classes.
• 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 Acme’s tools.

16
Session Context Interface

<<Interface>>
EJBContext

getEJBHome()
getEnvironment()
getCallerIdentity()
isCallerInRole()
getUserTransaction()
setRollBackOnly()

<<Interface>>
SessionContext

getEJBObject()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

The SessionContext interface


A container provides the session bean instances with a SessionContext, which gives the
session bean instance access to the instance’s context maintained by the container. The
SessionContext interface has the following methods:
•The getEJBObject method returns the session bean’s remote interface.
•The getEJBHome method returns the session bean’s home interface.
•The getCallerPrincipal method returns the java.security.Principal that identifies the invoker
of the bean instance’s EJB™ object.
•The isCallerInRole method tests if the session bean instance’s 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.

17
javax.EJB™ Session Bean
Interface
<<Interface>>
java.io.serializable

<<Interface>>
EnterpriseBean

<<Interface>>
SessionBean

setSessionContext()
ejbRemove()
ejbActivate()
ejbPassivate()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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.

18
Session Bean Implementation

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the session
bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

• 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()

public interface ShoppingCart extends javax.ejb.EJBObject {

public void addItem(String itemId, int qty) throws


java.rmi.RemoteException;
public void removeItem(String itemId, int qty) throws
java.rmi.RemoteException;
public Hashtable getItems() throws
java.rmi.RemoteException;

}
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Business method delegation


The session bean’s remote interface defines the business methods callable by a client. The
session bean’s remote interface is implemented by the session EJBObject class generated
by the container tools. The session EJBObject class delegates an invocation of a business
method to the matching business method that is implemented in the session bean class.
Requirements for the session bean’s 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 bean’s 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.

20
Session Bean Implementation

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the session
bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

• 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

Must return Cart create(args)


remote interface

public interface ShoppingCartHome extends javax.ejb.EJBHome {

Cart create(String custId) throws java.rmi.RemoteException,


javax.ejb.CreateException;

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the
session bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

• 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()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

business method ejbActivate()


© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

25
3) ShoppingCartBean: Implement Shopping
Cart Interface Business Methods

public class ShoppingCartBean implements SessionBean {


// instance variables
private Hashtable cart=null;
int customerId;
private SessionContext sessionContext=null;

// implement ShoppingCart interface business methods

public void addItem (String itemId,int qty) {


cart.put(itemId,new Integer(qty));
}
public void removeItem(String itemId, int qty){
cart.remove(itemId);
}

public Hashtable getItems() {


return cart;
}
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Bean business-logic methods:


These methods must match the methods defined in this EJB's remote
interface, ShoppingCart. Although ShoppingCartBean does not implement the
ShoppingCart interface, generated stub classes on the client side will. Calls on
those classes will be forwarded to the ShoppingCartBean.

26
Creating a Stateful Session

Session bean
client EJBHome EJBObject instance
context

create()
new

new

new

setSessionContext()

ejbCreate(args)

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

//create/store Client specific state (instance variables

public void ejbCreate(int customerId) {


this.cart = new Hashtable();
this.customerId= customerId;
}

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Session bean’s ejbCreate(...) methods


A client creates a session bean instance using one of the create methods
defined in the session bean’s home interface. The session bean’s home
interface is provided by the bean developer; its implementation is generated by
the deployment tools provided by the container provider.
The input parameters sent from the client are passed to the ejbCreate method.
Each session bean class must have at least one ejbCreate method. The number
and signatures of a session bean’s create methods are specific to each session
bean class. Since a session bean represents a specific, private conversation
between the bean and its client, its create parameters typically contain the
information the client uses to customize the bean instance for its use.

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()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

//associate a session bean instance with its context maintained by


the container.
public void setSessionContext(SessionContext sc){
this.sessionContext=sc;
}

// signals the instance it has just been reactivated.


// open any needed resources
public void ejbActivate() {}

// signals the intent of the container to passivate the instance


// close any open resources
public void ejbPassivate() {}

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

•The bean’s 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 ejbPassivate notification signals the intent of the container to passivate
the instance.
•The ejbActivate notification signals the instance it has just been reactivated.
Because containers automatically maintain the conversational state of a
session bean instance when it is passivated, most session beans can ignore
these notifications. Their purpose is to allow session beans to maintain those
open resources that need to be closed prior to an instance’s passivation and
then reopened during an instance’s activation.

30
Removal of a Stateful Session
Object
bean
client EJBHome EJBObject context instance

remove()

ejbRemove()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

// signals that the instance is in the process of being removed by


// the container, release resources
public void ejbRemove() {
this.cart = null;
this.customerId= null;
}

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

•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 same resources that it releases in the ejbPassivate
method.

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

business method ejbActivate()


© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

Method Name Exception It Throws Reason for Throwing


ejbCreate CreateException An input parameter is
invalid
ejbFindByXXXX ObjectNotFoundException The database row for
(subclass of the requested entity
FinderException) bean is cannot be found.

ejbRemove RemoveException The entity bean's row


cannot be deleted from
the database.
ejbLoad NoSuchEntityException The database row to be
loaded cannot be found.
ejbStore NoSuchEntityException The database row to be
updated cannot be
found.
(all methods) EJBException A system problem has
been encountered.

© 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 35
the transaction. However, if an application exception is thrown within a
Session Bean Implementation

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the session
bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

36
4) Compile the Remote & Home Interfaces and
Implementation Class.

javac –classpath $J2EE_HOME/lib/j2ee.jar


ShoppingCart.java
ShoppingCartHome.java
ShoppingCartEJB.java

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

37
Session Bean Implementation

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the session
bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

38
5) Create Deployment Descriptor

deploytool
Set the values for the class names, transaction
attributes,
Environment values, resource references…

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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>

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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>

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

43
Session Bean Implementation

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the session
bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

44
6) Package in an ejb-jar File.

packager –ejbJar Cart.class


CartEJB.class CartHome.class
ejb-jar.xml

Cart
CartHome
CartEJB
Interfaces bean
XML DD
Deployment
Descriptor

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

45
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

46
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

47
Session Bean Implementation

1. Define the session bean’s remote


interface (cart).
2. Define a home interface (CartHome)
for the session bean.
3. Write the business logic in the session
bean class (CartBean).
4. Compile the remote interface, home
interface, and implementation class.
5. Define a deployment descriptor
specifying any declarative metadata.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

Server Jar: CartHome Cart


Skeletons and
Client Jar: implementations CartEJB,
CartHome Cart Stubs Servlet, JSP classes

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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

1. Use JNDI to lookup CartHome.


2. Call CartHome’s create methods to get
the Cart interface.
3. Call business methods thru Cart
remote interface.

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

52
Cart Client Code

//Create an InitialContext (starting point)


javax.naming.Context ic = new javax.naming.InitialContext();

String jndiName = “ShoppingCart”;


// lookup the EJBHome interface using the JNDI name given in
deployment descriptor
java.lang.Object objref = ic.lookup(jndiName);

CartHome cartHome = (CartHome)


PortableRemoteObject.narrow(objref,CartHome.class);

Cart cart = cartHome.create(41476633);

// call business methods


cart.addItem( 111222, 1);

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

1) Use JNDI name services to locate a name server:


Create an InitialContext (starting point) optionally with server properties.
2)lookup the EJBHome interface using the JNDI name given in deployment
descriptor
-lookup returns a stub reference to the object implementation of
ShoppingCartHome
3)call create or find to get a reference to the ShoppingCart EJBObject stub.
4)call ShoppingCart business methods

53
Exercise: Implement Duke’s Bookstore
ShoppingCart Stateful Session Bean

Use Case Scenarios

customer
Remove/add Item from/to cart

customer
Get Items in cart…

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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()

© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

55

You might also like