211 48 461KB
English Pages 61
Developing a St at eless Session Ent erprise J ava Bean
1
Session Bean Tut orial Agenda: How t o develop and deploy a st at eless session bean by example: • W hat is a st at eless session bean • When t o use session beans • St eps f or implement ing a st at eless session bean – Over view of EJ B™ API s – Example St at eless session bean implement at ion • Assembling an deploying t he example session bean • Writ ing and running t he client of t he example session bean © Copyright 2000 Sun Microsystems, Inc., All rights reserved.
2
What Are Session Beans? • Session beans are t ypically used f or business process or cont rol logic t hat spans mult iple ent it y beans session
entity
Entity Bean
entity
Entity Bean
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 I s a Session Bean? • I s r elat ively short - lived (lif e t ypically is t hat of it s client ). • I s removed when t he EJ B™ server crashes. • Does not represent dat a in dat abase, but can access it . • Execut es on behalf of a single client . • Can be t ransact ion aware.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
4
When t o Use Session Beans? • Use Session beans t o model process or cont rol obj ect s specif ic t o a par t icular client . • To model workf low, pr ocesses or t asks, manage act ivit ies (make r eser vat ion, pur chase...). • To Coordinat e pr ocesses bet ween ent it y beans, cont rol int eract ions of beans. • To put business applicat ion logic on t he Ser ver Side.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
5
Session vs. Ent it y Beans
Session Beans Entity Beans • Represent a business process • One instance per client • Short-lived: Life of client is life of bean • Transient • Doesn’t 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.
6
2 Types of Session Beans • St at eless: execut e a r equest and r et ur n a r esult wit hout saving any client specif ic st at e inf or mat ion. – t ransient – t emporary piece of business logic needed by a specif ic client f or a limit ed t ime span
• St at ef ul: maint ains client specif ic st at e. 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
St at eless Session Beans oSt at eless beans:
o Do not r et ain client inf or mat ion f r om one met hod invocat ion t o t he next . o Client passes any needed inf or mat ion as par amet er s t o t he business met hods. oUsed mainly t o pr ovide a pool of beans t o handle f requent but brief request s. oThe EJ B™ ser ver t ransparent ly reuses inst ances of t he bean t o ser vice dif f erent client s. © 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
St at eless vs St at ef ul
Cart items
request with parameters needed for processing
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
9
St at eless May Use Fewer Resources: o Number of St at eless Session Beans needed < Number of Client s: o Can be recycled. o Number of inst ances t o cr eat e is minimized. o Short er lif e (no client session) opt imizes r esour ce usage. o I mpr oved per f or mance due t o f ewer connect ions acr oss t he net wor k .
oBut may r equir e t he client t o maint ain st at e inf or mat ion on t he 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 t o use St at eless Session Beans? The f ollowing guide- lines can be used f or modeling st at eless session component s: • Reusable service obj ect s • May provide high perf ormance • Not t ied up t o one client af t er met hod complet es. • Need t o operat e on mult iple rows at a t ime (read- only view) • Provides procedural view of dat a, ( Ent it y Bean pr ovides obj ect view of dat a.) © 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
I mplement ing a Session Bean • I n t his session we will discuss an example st at eless session bean, we will discuss st at ef ul in a lat er session. • As an example we will use t he ATM session bean f r om t he bank account t r ansf er scenar io.
© 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
Account
ATM 0…*
transfer()
balance
0…*
accesses
withdraw() deposit()
Checking Account
Savings Account
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
14
Example Scenario: Sequence Diagram
: Customer
ATM
saving account
checking account
1: transfer() 2: debit()
3: credit())
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
15
Example Scenario: EJ B
debit Client
ATM Session bean
Transfer
credit
Account Entity Bean account1
Account Entity Bean
account2
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
16
Session Bean I mplement at ion 1. Cr eat e t he remot e int erf ace f or t he bean. 2. Cr eat e t he bean’s home int erf ace. 3. Cr eat e t he bean’s implement at ion class. 4. Compile t he r emot e int er f ace, home int er f ace, and implement at ion class. 5. Cr eat e a deployment descript or . 6. Package in an ej b- j ar f ile. 7. Deploy t he ent er pr ise applicat ion. © 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
EJ B™ API Review
java.RMI.Remote
java.io.serializable
JDK
EnterpriseBean
EJBHome
EJBObject
javax.ejb
SessionBean
AtmHome
xxxatm EJBHome
Atm
xxxatm EJBObject
AtmBean
xxx AtmBean
Bean provider xxx Cont ainer 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
j avax. EJ B™ Client I nt erf aces
java.RMI.Remote extends
EJBHome
remove() getEJBMetaData() getHomeHandle()
EJBObject
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
j avax. EJ B™ Server I nt erf aces
java.io.serializable
EnterpriseBean
SessionBean
setSessionContext() ejbRemove() ejbActivate() ejbPassivate()
EntityBean
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
j avax. EJ B™ Server I nt erf aces Cont .
EJBContext
getEJBHome() getEnvironment() getCallerIdentity() isCallerInRole() getUserTransaction() setRollBackOnly()
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
Dif f erences From Ent it y Bean Session • I mplement s SessionBean int erf ace • Does not use primary key obj ect • Uses creat e met hod t o creat e inst ance, st at ef ul t o init ialize local dat a
Ent it y • I mplement s Ent it yBean int erf ace
• Uses primary key obj ect • Uses creat e, and callback met hods t o creat e, st ore/ updat e dat a in dat abase
© 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 I mplement at ion 1. Creat e t he remot e int erf ace f or t he bean. 2. Cr eat e t he bean’s home int er f ace. 3. Cr eat e t he bean’s implement at ion class. 4. Compile t he r emot e int er f ace, home int er f ace, and implement at ion class. 5. Cr eat e a deployment descr ipt or . 6. Package in an ej b-j ar f ile. 7. Deploy t he ent er pr ise applicat ion.
© 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) Creat e t he Remot e I nt erf ace
EJBObject
extends
Atm transfer()
Def ine Business Met hods: public int erf ace At m ext ends j avax. ej b. EJ BObj ect { public void t r ansf er (int f romAcct I d, int t oAcct I d, double amount ) t hr ows j ava.r mi.Remot eExcept ion,I nsuf f icient FundsExcept ion;
} © 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 I mplement at ion 1. Cr eat e t he r emot e int er f ace f or t he bean. 2. Creat e t he bean’s home int erf ace. 3. Cr eat e t he bean’s implement at ion class. 4. Compile t he r emot e int er f ace, home int er f ace, and implement at ion class. 5. Cr eat e a deployment descr ipt or . 6. Package in an ej b-j ar f ile. 7. Deploy t he ent er pr ise applicat ion.
© 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) Creat e t he Home I nt erf ace
EJBHome
AtmHome create()
Ret ur ns At m r emot e int er f ace
Def ine Creat e Met hods: public
int erf ace At mHome ext ends j avax. ej b. EJ BHome {
At m cr eat e() t hr ows j ava.r mi.Remot eExcept ion, j avax.ej b.Cr eat eExcept ion;
}
© 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 interface. • The throws clause must include javax.ejb.CreateException.
26
Session Bean I mplement at ion 1. Cr eat e t he r emot e int er f ace f or t he bean. 2. Cr eat e t he bean’s home int er f ace. 3. Creat e t he bean’s implement at ion class. 4. Compile t he r emot e int er f ace, home int er f ace, and implement at ion class. 5. Cr eat e a deployment descr ipt or . 6. Package in an ej b-j ar f ile. 7. Deploy t he ent er pr ise applicat ion. © 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) At mBean I mplement at ion
SessionBean
implements
setSessionContext() ejbRemove() ejbActivate() ejbPassivate()
Atm transfer() must match for container “glue”
AtmBean
transfer() ejbCreate() setSessionContext() ejbRemove() ejbActivate() ejbPassivate()
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
Lif ecycle of a St at eless 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
I nvocat ion of a Business Met hod 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) At mBean: I mplement At m I nt erf ace Business Met hods public class At mBean implement s SessionBean { / / implement at m int erf ace business met hods public void t r ansf er (int f r omAcct I d, int t oAcct I d, double amount ) t hr ows I nsuf f icient FundsExcept ion, Finder Except ion { t ry { f r omAccount = account Home. f indByPrimaryKey(new I nt eger(f romAcct I d)); } cat ch(Finder Except ion ex) { t hr ow new Finder Except ion("Couldnt f ind account "+f r omAcct I d ); } try { t oAccount = account Home. f indByPrimaryKey(new I nt eger(t oAcct I d)); } cat ch(Finder Except ion ex) { t hr ow new Finder Except ion("Couldnt f ind account "); } try { f r omAccount . wit hdraw(amount ); t oAccount . deposit (amount ); } cat ch(I nsuf f icient FundsExcept ion ex) { t hr ow new I nsuf f icient FundsExcept ion("I nsuf f icient f unds " + f r omAcct I d); } © 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
Creat ing a St at eless Session Bean I nst ance client
EJBHome EJBObject
context
bean instance
create() new
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
32
Adding I nst ance of St at eless Session Bean t o a Met hod- 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) At mBean: I mplement Home I nt erf ace Creat e Met hod Ret urns void
//
implement at mHome int erf ace creat e
pr ivat e st at ic Account Home account Home = null; public void ej bCreat e (){ t ry { Cont ext ic = new I nit ialCont ext (); j ava. lang. Obj ect obj ref = ic. lookup("j ava: comp/ env/ ej b/ Account "); account Home=(Account Home)Port ableRemot eObj ect . narrow(obj r ef , Account Home. class); } cat ch (NamingExcept ion ne) { Syst em.er r .pr int ln("ej bCr eat e: Caught unexpect ed NamingExcept ion:"); }
} EXAMPLE DEPLOYMENT DESCRI PTOR XML FOR EJ B™ REFERENCE
ej b/ Account Ent it y package. Account Home package. Account
© 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 I nst ance of St at eless 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 St at eless Session Bean I nst ance client
EJBHome EJBObject
context
bean instance
remove()
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
36
3) At mBean: I mplement Session I nt erf ace Cont ainer Callback Met hods / / save t he session cont ext in an inst ance variable public void set SessionCont ext (SessionCont ext sc) { t his.cont ext = sc; }
/ / release resources allocat ed in ej bCreat e public void ej bRemove() t hr ows RemoveExcept ion { account Home = null; }
/ / St at eless Session Beans are not act ivat ed/ passivat ed / / so t hese met hods are always empt y public void ej bAct ivat e() { } public void ej bPassivat e() { }
© 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
Lif ecycle of a St at eless 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 I mplement at ion 1. Cr eat e t he r emot e int er f ace f or t he bean. 2. Cr eat e t he bean’s home int er f ace. 3. Cr eat e t he bean’s implement at ion class. 4. Compile t he remot e int erf ace, home int erf ace, and implement at ion class. 5. Cr eat e a deployment descr ipt or . 6. Package in an ej b-j ar f ile. 7. Deploy t he ent er pr ise applicat ion.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
39
4) Compile t he Remot e & Home I nt erf aces and I mplement at ion 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 I mplement at ion 1. Cr eat e t he r emot e int er f ace f or t he bean. 2. Cr eat e t he bean’s home int er f ace. 3. Cr eat e t he bean’s implement at ion class. 4. Compile t he r emot e int er f ace, home int er f ace, and implement at ion class. 5. Creat e a deployment descript or. 6. Package in an ej b-j ar f ile. 7. Deploy t he ent er pr ise applicat ion.
© 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 I nt ro
Processing Instruction (PI)
Document Type Definition(DTD)
Element Attribute
The XML Companion Neil Bradley Addison-Wesley
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
Processing Instruction (PI) Document Type Definition(DTD) Element Attribute
42
EJ B descript or composit ion
no description Atm
no description AtmBean AtmBean AtmHome Atm AtmEJB Stateless Container
no description ejb/Account Entity AccountHome Account
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
47
5) Creat e DD Cont .
AtmBean Remote transfer
Required
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
48
Session Bean I mplement at ion 1. Cr eat e t he r emot e int er f ace f or t he bean. 2. Cr eat e t he bean’s home int er f ace. 3. Cr eat e t he bean’s implement at ion class. 4. Compile t he r emot e int er f ace, home int er f ace, and implement at ion class. 5. Cr eat e a deployment descr ipt or . 6. Package in an ej b- j ar f ile. 7. Deploy t he ent er pr ise applicat ion.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
49
6) Package in an ej b- j ar File. packager –ejbJar Atm.class:AtmEJB.class:AtmHome.class Atm-ejb-jar.xml Atm.jar
At m At mHome I nt erf aces
At mEJ B bean XML DD
Deployment Descript or
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
50
6) Package in an ej b- j ar File.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
51
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
52
Session Bean I mplement at ion 1. Cr eat e t he r emot e int er f ace f or t he bean. 2. Cr eat e t he bean’s home int er f ace. 3. Cr eat e t he bean’s implement at ion class. 4. Compile t he r emot e int er f ace, home int er f ace, and implement at ion class. 5. Cr eat e a deployment descr ipt or . 6. Package in an ej b-j ar f ile. 7. Deploy t he ent erprise applicat ion.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
53
7) Deploy t he Ent erprise Applicat ion Application jar: Atm, Account
AtmEJB.jar, Account.EJBjar
EJBHome EJBObject interfaces, Atm, Account beans Deployment tool
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.
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
Creat e a Client 1. Use J NDI t o lookup EJ B’s home int er f ace. 2. Call home’s creat e met hod t o get t he EJ B™ remot e obj ect int er f ace. 3. Call bean’s business met hods t hr u r emot e int er f ace.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
56
ATM Client Code / / creat e an init ial cont ext (st art ing point in name t ree) j avax. naming. Cont ext ic =new j avax. naming. I nit ialCont ext (); / / lookup j ndi name (set by deployer in deployment descript or) j ava. lang. Obj ect obj ref = ic. lookup("At m"); At mHome home = (At mHome)Port ableRemot eObj ect . narrow( obj ref , At mHome. class); / / call At mHome Creat e met hod t o get At m int erf ace At m at m = home. creat e(); / / call At m business met hods at m. t ransf er(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 Ent it y Bean JNDI name service EJBHome
transfer
find EJBObject EJBObject
Client
find
Atm Bean
Account 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 I mplement Cat alog St at eless Session Bean Use Case Scenarios
customer
customer
customer
List Books in Store
Search for books by subject…
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
St at eless Services: Cat alog Session EJ B 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
Cat alogEJ B
Catalog getBooks() getBookDetails() findBooksBySubject()
BookDetails
CatalogEJB
CatalogHome create()
getBooks() getBookDetails() findBooksBySubject() ejbCreate() setSessionContext() ejbRemove() ejbActivate() ejbPassivate()
ISBN title author publisher subject description price getISBN() getTitle() getAuthor() getPrice() getDescription() getPublisher()
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
61