You are on page 1of 61

Developing a Stateless Session Enterprise Java Bean

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.

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.

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.

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.

Session vs. Entity Beans Session Beans Entity Beans


Represent a business process One instance per client Short-lived: Life of client is life of bean Transient Doesnt survive server crashes May be transactional Represent business data Shared instance for multiple clients Long-lived: as long as data in database Persistent Survive server crashes Always 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.

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.

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

Stateless vs Stateful

Cart items

request with parameters needed for processing

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

Stateless May Use Fewer Resources:


oNumber of Stateless Session Beans needed < Number of Clients:

oBut may require the client to maintain state information on the client side which can mean more complex client code.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

o Can be recycled. o Number of instances to create is minimized. o Shorter life (no client session) optimizes resource usage. o Improved performance due to fewer connections across the network.

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

10

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
0* 0*

Account
balance

transfer()

accesses

withdraw() deposit()

Checking Account

Savings Account

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

14

Example Scenario: Sequence Diagram


ATM saving account checking account

: Customer

1: transfer() 2: debit()

3: credit())

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

15

Example Scenario: EJB

debit Client ATM Session bean credit

Account Entity Bean


account1 account2

Transfer

Account Entity Bean

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

16

Session Bean Implementation


1. 2. 3. 4. 5. 6. 7. Create the remote interface for the bean. Create the beans home interface. Create the beans implementation class. Compile the remote interface, home interface, and implementation class. Create a deployment descriptor. Package in an ejb-jar file. Deploy the enterprise application.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

What the ATM session Bean provider is responsible for: Define the session Beans remote interface (Atm). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for a RMI-IIOP remote interface. The remote interface must be defined as public. Write the business logic in the session Bean class (AtmBean). The enterprise Bean must implement the javax.ejb.SessionBean interface, and define the ejbCreate(...) methods invoked at an EJB object creation. Define a home interface (AtmHome) for the enterprise Bean. The home interface must be defined as public, extend the javax.ejb.EJBHome interface, and follow the standard rules for RMI-IIOP remote interfaces. Define a deployment descriptor specifying any declarative metadata that the session Bean provider wishes to pass with the Bean to the next stage of the development/deployment work-flow.

17

EJB API Review


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

JDK

<<Interface>> EnterpriseBean <<Interface>> EJBHome <<Interface>> EJBObject <<Interface>> SessionBean

javax.ejb

<<Interface>> AtmHome

<<Interface>> Atm

AtmBean

Bean provider xxx Container provider

xxxatm EJBHome

xxxatm EJBObject

xxx AtmBean

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 beans remote interface. The tools also generate the classes that implement the communication protocol specific artifacts for the remote interface. Generate the implementation of the session Bean class suitable for the xxx container (xxxAtmBean). xxxAtmBean includes the business logic from the AtmBean class mixed with the services defined in the xxxBean class. xxx tools can use inheritance, delegation, and code generation to achieve a mix-in of the two classes. Generate the class (xxxAtmHome) that implements the session beans home interface. Generate the class (xxxAtmMetaData) that implements the javax.ejb.EJBMetaData interface for the Atm Bean.

18

javax.EJB Client Interfaces


<<Interface>> java.RMI.Remote extends

<<Interface>> EJBHome

<<Interface>> EJBObject

remove() getEJBMetaData() getHomeHandle()

getEJBHome() remove() 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>> SessionBean

<<Interface>> EntityBean

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

setEntityContext() unsetEntityContext ejbRemove() ejbActivate() 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>> SessionContext

<<Interface>> 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 instances context maintained by the container. This give information about the beans home object, current transaction information, security role information. The SessionContext interface has the following methods: The getEJBObject method returns the session beans remote interface. The getEJBHome method returns the session beans home interface. The getCallerPrincipal method returns the java.security.Principal that identifies the invoker of the bean instances EJB object. The isCallerInRole method tests if the session bean instances caller has a particular role. The setRollbackOnly method allows the instance to mark the current transaction such that the only outcome of the transaction is a rollback. Only instances of a session bean with container-managed transaction demarcation can use this method. The getRollbackOnly method allows the instance to test if the current transaction has been marked for rollback. Only instances of a session bean with container-managed transaction demarcation can use this method. The getUserTransaction method returns the javax.transaction.UserTransaction interface. The instance can use this interface to demarcate transactions and to obtain transaction status. Only instances of a session bean with bean-managed transaction demarcation can use this method.

21

Differences From Entity Bean


Session
Entity Implements EntityBean interface Uses primary key object Uses create, and callback methods to create,store/update data in database

Implements SessionBean interface Does not use primary key object Uses create method to create instance, stateful to initialize local data

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 beans home interface. 3. Create the beans 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 Beans remote interface (Atm). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for a RMI-IIOP remote interface. The remote interface must be defined as public.

23

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 beans remote interface The following are the requirements for the session beans remote interface: The interface must extend the javax.ejb.EJBObject interface. The methods defined in this interface must follow the rules for RMI/IIOP. This means that their arguments and return values must be of valid types for RMI/IIOP, and their throws clause must include the java.rmi.RemoteException. The remote interface is allowed to have super interfaces. Use of interface inheritance is subject to the RMI/IIOP rules for the definition of remote interfaces. For each method defined in the remote interface, there must be a matching method in the session beans class. The matching method must have: The same name. The same number and types of arguments, and the same return type. All the exceptions defined in the throws clause of the matching method of the session bean class must be defined in the throws clause of the method of the remote interface.

24

Session Bean Implementation


1. 2. 3. 4. 5. 6. 7. Create the remote interface for the bean. Create the beans home interface. Create the beans implementation class. Compile the remote interface, home interface, and implementation class. Create a deployment descriptor. Package in an ejb-jar file. 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

Returns Atm remote interface

create()

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 beans home interface requirements: The interface must extend the javax.ejb.EJBHome interface. The methods defined in this interface must follow the rules for RMI/IIOP. This means that their arguments and return values must be of valid types for RMI/IIOP, and that their throws clause must include the java.rmi.RemoteException. The home interface is allowed to have superinterfaces. Use of interface inheritance is subject to the RMI/IIOP rules for the definition of remote interfaces. A session beans home interface must define one or more create(...) methods. (stateless only 1) Each create method must be named create, and it must match one of the ejbCreate methods defined in the session bean class. The matching ejbCreate method must have the same number and types of arguments. (Note that the return type is different.) (stateless no arguments) The return type for a create method must be the session beans remote interface type. All the exceptions defined in the throws clause of an ejbCreate method of the session bean class must be defined in the throws clause of the matching create method of the home interface. The throws clause must include javax.ejb.CreateException.

26

Session Bean Implementation


1. 2. 3. 4. 5. 6. 7. Create the remote interface for the bean. Create the beans home interface. Create the beans implementation class. Compile the remote interface, home interface, and implementation class. Create a deployment descriptor. Package in an ejb-jar file. 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() <<Interface>> Atm transfer() must match for container glue <<Interface>> AtmHome create()

AtmBean

transfer() ejbCreate() setSessionContext() ejbRemove() ejbActivate() ejbPassivate()

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
EJB Instance

business method

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

29

Invocation of a Business Method


client EJB Home EJB session Object context
synchro nization

trans bean instance action

data base

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.1an EJB 1.1 compliant enterprise bean should throw the javax.ejb.EJBException or another RuntimeException to indicate non-application exceptions to the Container

31

Creating a Stateless Session Bean Instance


client EJBHome EJBObject context bean instance

create() new

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

32

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


client
EJB Home EJB Object

container

session context

synchronization

bean instance

trans action

data base

new

new setSessionContext() ejbCreate()

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

33

3) AtmBean: Implement Home Interface Create Method


//
Returns void private static AccountHome accountHome = null; public void ejbCreate (){ try { Context ic = new InitialContext();

implement atmHome interface create

} EXAMPLE DEPLOYMENT DESCRIPTOR XML FOR EJB REFERENCE <ejb-ref> <ejb-ref-name>ejb/Account</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <home>package.AccountHome</home> <remote>package.Account</remote> </ejb-ref>
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

java.lang.Object objref = ic.lookup("java:comp/env/ejb/Account"); accountHome=(AccountHome)PortableRemoteObject.narrow(objref, AccountHome.class); } catch (NamingException ne) { System.err.println("ejbCreate: Caught unexpected NamingException:"); }

Bean create methods must match the methods defined in this EJB's home interface, AtmHome. Container tools generate the implementation of the AtmHome class and the client stub and server skeleton classes. Calls on those classes will be forwarded to the AtmBean. A stateless session bean must have only one ejbCreate method, which must return void and contain no arguments. In a stateless session bean, none of the methods depend on the values of variables set by any other method, except for the ejbCreate, setSessionContext methods which set the initial (identical) state of each bean instance. The term stateless signifies that an instance has no state for a specific client. However, the instance variables of the stateless session bean can contain non-client specific state across client-invoked method calls. Examples of such states include an open database connection or an object reference to an EJB object. ejbCreate method The stateless session bean class must define one ejbCreate(...) methods whose signature must follow these rules: The method name must be ejbCreate. The method must be declared as public. The method must not be declared as final or static. The return type must be void. The methods arguments must be legal types for RMI/IIOP. The throws clause may define arbitrary application exceptions, possibly including the javax.ejb.CreateException.

34

Removing Instance of Stateless Session Bean From Ready Pool


client
EJB Home EJB Object

container

session context

synchronization

bean instance

trans action

data base

ejbRemove()

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

35

Removal of a Stateless Session Bean Instance


client EJBHome EJBObject context bean instance

remove()

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

36

3) AtmBean: Implement Session Interface Container Callback Methods


public void setSessionContext(SessionContext sc) { this.context= sc; } public void ejbRemove() throws RemoveException { accountHome = null; }

// save the session context in an instance variable

// release resources allocated in ejbCreate

public void ejbActivate() { } public void ejbPassivate() { }

// Stateless Session Beans are not activated/passivated // so these methods are always empty

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 beans container calls the setSessionContext method to associate a session bean instance with its context maintained by the container. Typically, a session bean instance retains its session context as part of its conversational state. The ejbRemove notification signals that the instance is in the process of being removed by the container. In the ejbRemove method, the instance typically releases the resources that it allocated in the ejbCreate method. ejbActivate/ejbPassivate: All Stateless Session bean instances are equivalent when they are not involved in serving a client-invoked method. A container only needs to retain the number of instances required to service the current client load. Due to client think time, this number is typically much smaller than the number of active clients. Passivation is not needed for stateless sessions. The container creates another stateless session bean instance if one is needed to handle an increase in client work load. If a stateless session bean is not needed to handle the current client work load, the container can destroy it.

37

Lifecycle of a Stateless Session Bean

does not exist

1) newInstance()

ejbRemove()
2) setSessioncontext() 3)ejbCreate()

method-ready pool
EJB Instance

business method

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

38

Session Bean Implementation


1. 2. 3. 4. 5. 6. 7. Create the remote interface for the bean. Create the beans home interface. Create the beans implementation class. Compile the remote interface, home interface, and implementation class. Create a deployment descriptor. Package in an ejb-jar file. 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. 2. 3. 4. 5. 6. 7. Create the remote interface for the bean. Create the beans home interface. Create the beans implementation class. Compile the remote interface, home interface, and implementation class. Create a deployment descriptor. Package in an ejb-jar file. Deploy the enterprise application.

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

What the ATM session Bean provider is responsible for: Define the session Beans remote interface (Atm). The remote interface defines the business methods callable by a client. The remote interface must extend the javax.ejb.EJBObject interface, and follow the standard rules for a RMI-IIOP remote interface. The remote interface must be defined as public. Write the business logic in the session Bean class (AtmBean). The enterprise Bean must implement the javax.ejb.SessionBean interface, and define the ejbCreate(...) methods invoked at an EJB object creation. Define a home interface (AtmHome) for the enterprise Bean. The home interface must be defined as public, extend the javax.ejb.EJBHome interface, and follow the standard rules for RMI-IIOP remote interfaces. Define a deployment descriptor specifying any declarative metadata that the session Bean provider wishes to pass with the Bean to the next stage of the development/deployment work-flow.

41

XML Short Intro


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

<!DOCTYPE order SYSTEM "order.dtd"> Document Type Definition(DTD) <order id="A002"> <book isbn="0-201-34285-5"> <title>The XML Companion</title> <author>Neil Bradley</author> <publisher>Addison-Wesley</publisher> </book> </order> Element Attribute

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 . . . jar archive </session> </enterprise-beans>

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

Assembly data

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 beans external dependencies. Providing structural information in the deployment descriptor is mandatory for the ejb-jar file producer. The structural information cannot, in general, be changed because doing so could break the enterprise beans function. Application assembly information. Application assembly information describes how the enterprise bean (or beans) in the ejb-jar file is composed into a larger application deployment unit. Providing assembly information in the deployment descriptor is optional for the ejb-jar file producer. Assembly level information can be changed without breaking the enterprise beans function, although doing so may alter the behavior of an assembled application.

43

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. 2. 3. 4. 5. 6. 7. Create the remote interface for the bean. Create the beans home interface. Create the beans implementation class. Compile the remote interface, home interface, and implementation class. Create a deployment descriptor. Package in an ejb-jar file. 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 AtmHome Interfaces

AtmEJB bean
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. 2. 3. 4. 5. 6. 7. Create the remote interface for the bean. Create the beans home interface. Create the beans implementation class. Compile the remote interface, home interface, and implementation class. Create a deployment descriptor. Package in an ejb-jar file. Deploy the enterprise application.

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

53

7) Deploy the Enterprise Application


AtmEJB.jar, Account.EJBjar
Deployment tool

Application jar: Atm, Account


EJBHome EJBObject interfaces, Atm, Account beans

Deployment tool

Client Jar: : Atm, Account EJBHome EJBObject

Interfaces & Stubs

Server Jar: Atm and Account EJBHome EJBObject Stubs and Object implementations Enterprise Beans

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

J2EE Reference Implementation Deployment: Behind the Scenes 1. 2. The J2EE process opens the application JAR file, reads the deployment descriptors, and generates the home interface and EJBObject implementation for each Bean. The J2EE process compiles the home interface and the EJBObject implementations and then runs the rmic command on the class files. This step creates the stubs and skeletons for the home and remote objects. The server packages the generated classes into a server JAR file and stores the JAR file in the repository. The server creates a client JAR file that contains the home and remote interfaces and the stubs for the home and remote objects. The server sends the client JAR file to the deployer and saves the file according to the name chosen at the start of the deployment process. The location of the client JAR file must be added to the CLASSPATH environment variable on any client that calls the application. Then, at runtime, the appropriate stub classes can be loaded so that the client can successfully locate objects, for example, the home object for an enterprise bean in the application. The J2EE server starts a process which loads the server JAR file and creates containers for the enterprise beans and binds the beans to the JNDI names in the name server. At this point, the deployment process is complete.

3. 4.

5.

6. 7.

54

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 EJBs home interface. 2. Call homes create method to get the EJB remote object interface. 3. Call beans 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
Account Bean

transfer

find
EJBObject EJBObject

Client

Atm Bean

withdraw

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 ISBN title author description
CatalogEJB
g e tBooks() g e tBookDetails() findBooksBySubject() 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
getBooks() getBookDetails() findBooksBySubject() ejbCreate() setSessionContext() ejbRemove() ejbActivate() ejbPassivate()

<<Interface>> CatalogHome create()

ISBN title author publisher subject description price getISBN() getTitle() getAuthor() getPrice() getDescription() getPublisher()

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

61

You might also like