You are on page 1of 61

Developing a Stateless Session

Enterprise Java Bean

1
Session Bean Tutorial Agenda:

How to develop and deploy a stateless


session bean by example:
• 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.

2
What Are Session Beans?

• Session beans are typically used


for business process or control
logic that spans multiple entity
beans
session

Entity Bean Entity Bean


entity entity entity

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

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
What Is a Session Bean?

• Is relatively short-lived (life typically is


that of its client).
• Is removed when the EJB™ server
crashes.
• Does not represent data in database, but
can access it.
• Executes on behalf of a single client.
• Can be transaction aware.

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

4
When to Use Session Beans?

• Use Session beans to model process or


control objects specific to a particular
client.
• To model workflow, processes or tasks,
manage activities (make reservation,
purchase...).
• To Coordinate processes between entity
beans, control interactions of beans.
• To put business application logic on the
Server Side.

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

5
Session vs. Entity Beans

Session Beans Entity Beans


• Represent a
•Represent business data
business process
• One instance per •Shared instance for
client multiple clients
• Short-lived: Life of
•Long-lived: as long as
client is life of bean
data in database
• Transient
• Doesn’t survive •Persistent
server crashes •Survive server crashes
• May be •Always Transactional
transactional
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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.

6
2 Types of Session Beans

• Stateless: execute a request and return


a result without saving any client specific
state information.
– transient
– temporary piece of business logic needed
by a specific client for a limited time
span
• Stateful: maintains client specific
state.

State instance data

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

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.

7
Stateless Session Beans
oStateless beans:
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

8
Stateless vs Stateful

Cart items

request with parameters


needed for processing

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

9
Stateless May Use Fewer
Resources:
oNumber of Stateless Session Beans
needed < Number of Clients:
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.
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.

Note: The difference in use of resources for stateless and stateful is application
server specific.

10
When to use Stateless Session
Beans?

The following guide-lines can be used for


modeling stateless session components:
• Reusable service objects
• May provide high performance
• Not tied up to one client after method
completes.
• Need to operate on multiple rows at a
time (read-only view)
• Provides procedural view of data,
(Entity Bean provides object view of
data.)
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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
Implementing a Session Bean

• In this session we will discuss an example


stateless session bean, we will discuss
stateful in a later session.
• As an example we will use the ATM
session bean from the bank account
transfer scenario.

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

12
Example Scenario: Use Case

Transfer
Money
Customer

Use Case: ATM customer transfers money from checking


to savings account

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

13
Example Scenario: Classes

ATM Account
balance
0…* 0…*
transfer() withdraw()
accesses
deposit()

Checking Savings
Account Account

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

14
Example Scenario: Sequence
Diagram

ATM saving checking


: Customer account account

1: transfer()
2: debit()

3: credit())

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

15
Example Scenario: EJB

debit Account
Entity Bean
ATM
Client account1
Session bean

Transfer account2
credit Account
Entity Bean

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

16
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation
class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

What the ATM session Bean provider is responsible for:


•Define the session Bean’s 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
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


AtmHome Atm
AtmBean
provider

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

The tools provided by xxx Corporation are responsible for the following:
•Generate the class (xxxRemoteAtm) 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 (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 bean’s
home interface.
•Generate the class (xxxAtmMetaData) that implements the
javax.ejb.EJBMetaData interface for the Atm Bean.

18
javax.EJB™ Client Interfaces

<<Interface>>
java.RMI.Remote

extends

<<Interface>>
<<Interface>>
EJBHome
EJBObject

getEJBHome()
remove()
getEJBMetaData()
remove()
getHomeHandle()
getHandle()
isIdentical()

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

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
javax.EJB™ Server Interfaces

<<Interface>>
java.io.serializable

<<Interface>>
EnterpriseBean

<<Interface>>
<<Interface>>
EntityBean
SessionBean

setEntityContext()
setSessionContext()
unsetEntityContext
ejbRemove()
ejbRemove()
ejbActivate()
ejbActivate()
ejbPassivate()
ejbPassivate()
ejbLoad()
ejbStore()

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

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
javax.EJB™ Server Interfaces
Cont.
<<Interface>>
EJBContext

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

<<Interface>> <<Interface>>
SessionContext EntityContext

getEJBObject() getEJBObject()
getPrimaryKey()

© 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. This give
information about the bean’s home object, current transaction information, security role
information…. 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.

21
Differences From Entity Bean

Session Entity
• Implements • Implements
SessionBean EntityBean interface
interface
• Does not use primary • Uses primary key
key object object
• Uses create method • Uses create, and
to create instance, callback methods to
stateful to initialize create,store/update
local data data in database

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

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
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

What the ATM session Bean provider is responsible for:


•Define the session Bean’s 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
1) Create the Remote Interface

<<Interface>>
EJBObject extends

<<Interface>>
Atm

transfer()

Define Business Methods:

public interface Atm extends javax.ejb.EJBObject {

public void transfer(int fromAcctId, int toAcctId, double amount)


throws java.rmi.RemoteException,InsufficientFundsException;

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

Session bean’s remote interface


The following are the 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.

24
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

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
2) Create the Home Interface

<<Interface>>
EJBHome

<<Interface>>
AtmHome

create()
Returns Atm
remote interface

Define Create Methods:

public interface AtmHome extends javax.ejb.EJBHome {

Atm create() throws java.rmi.RemoteException,


javax.ejb.CreateException;

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

Session bean’s 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 bean’s 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 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 inter-
face.
• The throws clause must include javax.ejb.CreateException.

26
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation
class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

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() AtmBean
<<Interface>>
Atm
transfer()
transfer() ejbCreate()
setSessionContext()
must match ejbRemove()
for container ejbActivate()
“glue” ejbPassivate()
<<Interface>>
AtmHome

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.

28
Lifecycle of a Stateless Session
Bean

does not
exist

1) newInstance()
ejbRemove()
2) setSessioncontext()

3)ejbCreate()

method-ready
pool
business method
EJB
Instance

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

29
Invocation of a Business Method

EJB EJB session synchro bean trans data


client nization instance action base
Home Object context

business method

business method

read, update data

register resource mgr

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

30
3) AtmBean: Implement Atm Interface
Business Methods
public class AtmBean implements SessionBean {

// implement atm interface business methods

public void transfer(int fromAcctId,int toAcctId,double amount)


throws InsufficientFundsException, FinderException {
try {
fromAccount = accountHome.findByPrimaryKey(new Integer(fromAcctId));
} catch(FinderException ex) {
throw new FinderException("Couldnt find account"+fromAcctId );
}
try {
toAccount = accountHome.findByPrimaryKey(new Integer(toAcctId));
}
catch(FinderException ex) {
throw new FinderException("Couldnt find account");
}
try {
fromAccount.withdraw(amount);
toAccount.deposit(amount);
} catch(InsufficientFundsException ex) {
throw new InsufficientFundsException("Insufficient funds " +
fromAcctId);
} © 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, 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.1—an EJB™ 1.1 compliant enterprise bean should throw the
javax.ejb.EJBException or another RuntimeException to indicate non-application exceptions
to the Container

31
Creating a Stateless Session Bean
Instance
bean
client EJBHome EJBObject context instance

create()
new

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

32
Adding Instance of Stateless Session
Bean to a Method-ready Pool

EJB EJB cont- session synchro- bean trans data


client Home Object ainer context nization instance action base

new

new

setSessionContext()

ejbCreate()

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

33
3) AtmBean: Implement Home
Interface Create Method
Returns void
// implement atmHome interface create
private static AccountHome accountHome = null;
public void ejbCreate (){
try {
Context ic = new InitialContext();

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:");
}
}
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.

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
Removing Instance of Stateless
Session Bean From Ready Pool

EJB EJB cont- session synchro- bean trans data


client Home Object ainer context nization instance action base

ejbRemove()

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

35
Removal of a Stateless Session
Bean Instance
bean
client EJBHome EJBObject context instance

remove()

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

36
3) AtmBean: Implement Session
Interface Container Callback Methods
// save the session context in an instance variable
public void setSessionContext(SessionContext sc) {
this.context= sc;
}

// release resources allocated in ejbCreate


public void ejbRemove() throws RemoveException {
accountHome = null;
}

// Stateless Session Beans are not activated/passivated


// so these methods are always empty
public void ejbActivate() {
}
public void ejbPassivate() {
}

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

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 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 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
Lifecycle of a Stateless Session
Bean

does not
exist

1) newInstance()
ejbRemove()
2) setSessioncontext()

3)ejbCreate()

method-ready
pool
business method
EJB
Instance

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

38
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

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

javac –classpath $J2EE_HOME/lib/j2ee.jar


Atm.java AtmHome.java
AtmEJB.java

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

40
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

What the ATM session Bean provider is responsible for:


•Define the session Bean’s 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
XML Short Intro

<?xml version="1.0"?> Processing Instruction (PI)

<!DOCTYPE order SYSTEM "order.dtd"> Document Type Definition(DTD)


<order id="A002"> Element
Attribute
<book isbn="0-201-34285-5">
<title>The XML Companion</title>
<author>Neil Bradley</author>
<publisher>Addison-Wesley</publisher>
</book>
</order>

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

Processing Instruction (PI)


Document Type Definition(DTD)
Element
Attribute

42
EJB descriptor composition

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC '-//SunMicrosystems Inc.//DTD>
<ejb-jar>
<enterprise-beans>
<session> Description of all EJBs in the
. . .
</session>
jar archive
</enterprise-beans>

<assembly-descriptor>
. . .
</assembly-descriptor> Assembly data
</ejb-jar>

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

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 bean’s 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 bean’s
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 bean’s
function, although doing so may alter the behavior of an assembled
application.

43
5) Create Deployment Descriptor

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

Set the values for the class names,


transaction attributes,
Environment values,resource references,
EJB™ references…

44
5) Create Deployment Descriptor

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

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
5) Create Deployment Descriptor

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

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
5) Create Deployment Descriptor

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems Inc.//DTD.. . >
<ejb-jar>
<description>no description</description>
<display-name>Atm</display-name>
<enterprise-beans>
<session>
<description>no description</description>
<display-name>AtmBean</display-name>
<ejb-name>AtmBean</ejb-name>
<home>AtmHome</home>
<remote>Atm</remote>
<ejb-class>AtmEJB</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<ejb-ref>
<description>no description</description>
<ejb-ref-name>ejb/Account</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<home>AccountHome</home>
<remote>Account</remote>
</ejb-ref>
</session>
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

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>

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

48
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

49
6) Package in an ejb-jar File.

packager –ejbJar
Atm.class:AtmEJB.class:AtmHome.class
Atm-ejb-jar.xml Atm.jar

Atm AtmEJB
AtmHome bean
Interfaces XML DD
Deployment
Descriptor

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

50
6) Package in an ejb-jar File.

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

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

52
Session Bean Implementation

1. Create the remote interface for the


bean.
2. Create the bean’s home interface.
3. Create the bean’s implementation class.
4. Compile the remote interface, home
interface, and implementation class.
5. Create a deployment descriptor.
6. Package in an ejb-jar file.
7. Deploy the enterprise application.

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

53
7) Deploy the Enterprise
Application
AtmEJB.jar, Application jar: Atm, Account
EJBHome EJBObject interfaces,
Account.EJBjar
Atm, Account beans
Deployment tool

Deployment tool

Server Jar: Atm and Account


Client Jar: : Atm, Account EJBHome EJBObject
EJBHome EJBObject Stubs and Object implementations
Interfaces & Stubs Enterprise Beans

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

J2EE™ Reference Implementation Deployment: Behind the Scenes


1. The J2EE™ process opens the application JAR file, reads the deployment descriptors, and
generates the home interface and EJBObject implementation for each Bean.
2. 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.
3. The server packages the generated classes into a server JAR file and stores the JAR file
in the repository.
4. 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.
5. 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.
6. 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.
7. At this point, the deployment process is complete.

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

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 EJB’s home


interface.
2. Call home’s create method to get the
EJB™ remote object interface.
3. Call bean’s business methods thru
remote interface.

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

56
ATM Client Code

// create an initial context (starting point in name tree)


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

// lookup jndi name (set by deployer in deployment


descriptor)
java.lang.Object objref = ic.lookup("Atm");

AtmHome home = (AtmHome)PortableRemoteObject.narrow(


objref, AtmHome.class);

//call AtmHome Create method to get Atm interface


Atm atm = home.create();

// call Atm business methods


atm.transfer(41476633, 4443332121, 100000);

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

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
Session Bean Accessing Entity Bean

JNDI name
service

EJBHome find

find
transfer EJBObject Account
EJBObject
Bean

Atm withdraw
Client Bean

deposit
EJBObject Account
Bean

server

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

Example of Sequence of events for Client calling the Transfer method on the
Atm remote interface stub.

58
Exercise: Design and Implement
Catalog Stateless Session Bean
Use Case Scenarios

customer
List Books in Store

customer
Search for books by subject…

customer
Get Book Details (by ISBN)…
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.

1)Customer finds book by ISBN


2)Customer searches for books by subject, author title….

59
Stateless Services:
Catalog Session EJB
product CatalogEJB

ISBN
g e tBooks()
title
g e tBookDetails()
author findBooksBySubject()
description ejbCreate()
s e tSessionContext()
e j b R e m o ve()
ejbActivate()
ejbPassivate()

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 ISBN
title
author
getBooks() publisher
getBookDetails() subject
findBooksBySubject() description
<<Interface>> price
ejbCreate()
CatalogHome setSessionContext()
getISBN()
ejbRemove() getTitle()
create() ejbActivate() getAuthor()
ejbPassivate() getPrice()
getDescription()
getPublisher()

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

61

You might also like