Tutorial for building j2ee applications using jboss and eclipse -4

xiaoxiao2021-03-06  82

Chapter 4.

Creating a stateful session bean

This chapter covers how to create a stateful session EJB component. Unlike stateless beans, stateful bean instances are associated with a particular client session and can therefore maintain information useful during the lifetime of that session. A classic and familiar example of this in a web e -commerce context is what of a shopping cart.

We'll try something a little less ambitious for the time being! This bean is similar to the StoreAccess Bean created in the previous chapter except that it will store the userID of the client, after authentication is successful.

Note: This Bean Will NOT BE USED Further In Tutorial, AS this Chapter Demonstrates How Stateful Beans Are Created.

Tasks:

Create a Stateful Session Bean named StoreAccessState. Add a business method in the bean named loginUser with the signature public String loginUser (String username, String password) Add a call back method ejbCreate with the signature public void ejbCreate (String userID) Generate the DAO interface . Access the DAO named StoreAccesDAOImpl under package au.com.tusc.dao, created and implemented in the previous chapter. This DAO has a method named loginUser, called by loginUser in the bean with the signature public String loginUser (String username, String password ) Deploy the storeAccessState bean. Create Your Test Client Named sessionStateClient under package au.com.tusc.client. Run Your Client and test the bean.

Create Stateless Bean:

Go to Package Explorer> Expand MyStore (Project) Node> SELECT SRC, RIGHT CLICK AND A MENU WILL POP UP.

On pop up menu> New> Lomboz EJB CREATION WIZARD.

Enter the package name au.com.tusc.sessionState, bean name StoreAccessState and select bean type as stateful> Finish.This will create package named au.com.tusc.sessionState under src and StoreAccessStateBean under that package as shown below.

As we can see from the figure above it has created a class level tag @ ejb.bean, which has assigned the bean type, name and its JNDI name which will be generated in the Home interface. This tag will also generate deployment descriptors in ejb -jar.xml and jboss.xml file as well overce you generate your EJB CLASSES, WHICH IS COVERED LATER ON THIS Chapter.

Note: It will generate the bean name, jndi-name and type of bean in file Also, the name of file is appended with word 'Bean' as you gave the name of the bean as StoreAccess only So be careful with your naming.. Convention, As you Only NEED Specify The Bean Name in The Wizard (IE. WIZARD WILL APPEND THAT I).

CREATE DAO Interface:

Since we are going to use a DAO to access the database for this Stateful Bean, we will use the StoreAccesDAOImpl class which was created and implemented in the previous chapter. This will provide the implementation for the generated DAO interface.

Now Go To your bean class and declare this Tag At Class Level (i: e; at top), as described Below to generate the Dao Interface.

@ Ejb.dao class = "au.com.tusc.sessionState.storeAccessStatedao"

Impl-class = "au.com.tusc.dao.storeAccessdaoImpl"

EXPAND The StoreAccessStateBean Node Under Package Explorer. Right Click and A Pop Up Menu Will Appear.

On That Menu Go to Lomboz J2EE> Add EJB TO MODULE. SELECT EJB MyStoremgr> OK.

Note: This Step is covered in Previous Chapter.Expand MyStoremgr Node Under MyStore Project In Package Explorer. Right Click and A Pop Up Menu Will Appear.

Go to Lomboz J2EE> Generate EJB CLASSES AS SHOWN in Figure At right.

EJB interfaces and helper classes are generated under 'ejbsrc' directory as shown on the right. Seven files are generated. StoreAccessState is our remote object interface. StoreAccessLocal is our local object interface. StoreAccessStateSession extends our bean class named StoreAccesStateBean. StoreAccessStateHome is our remote home interface. StoreAcessStateLocalHome is our local home interface. StoreAccessStateUtil is a helper class which has methods for accessing Home and LocalHome interface along with generating GUID. StoreAccesStateDAO is the DAO interface, which be implemented by StoreAccessDAOImpl under au.com.tusc.dao. StoreAccessStateDAO is generated by this tag declared in StoreAccesStateBean as shown below. If you do not declare this tag in that file it will not generate this interface. @ ejb.dao class = au.com.tusc.sessionState.StoreAccessStateDAO

Impl-class = au.com.tusc.dao.storeAccessDaoImpl Other Files of Interest Which Are generated Are Ejb-jar.xml 'and jboss.xml' under mystoremgr / meta-inf.

As shown in figure at right, a few descriptors are generated in the 'ejb-jar.xml' file. These descriptors are generated by the following tag declared in the StoreAccessBean file, which was generated by Lomboz. @ Ejb.bean name = StoreAccessSate

JNDI-NAME = StoreAccessStateBean

TYPE = Stateful

This Tag Also Genereates The Following Descriptors in jboss.xml as shown below.

Add Business Method:

The next step is to add a business method to the bean.go to storeaccesstatebean node> Right Click> SELECT New on Pop up Menu.

Select Lomboz EJB Method Wizard.

Note: this step is covered in the prep

Add a Business Method with The Following Signature ..

Public String Loginuser (String Username, String Password).

Select Method Type As Business and Interface As Remote As Shown Below ..

THIS WIZARD GENERATES A LOGINUSER METHOD IN OUR Bean Class, with the method level tag '@ Ejb.interface' Shown Below.

THIS TAG IS RESPONSIBLE for GENERATING this Method in The Remote Interface (in this case it is stores ".").

Now, this business method needs to invoke a method on the DAO, which encapsulates access to the database. So, add another tag on this method so that a method with this signature is generated in the DAO interface. We can then implement that method in our DAOImpl class so that our business method can get the desired result. @ dao.call name = loginUser Add this tag at the method level as shown on the right. Now generate your EJB classes again as shown in the steps earlier. OK, for Reference THESE ARE THE STEPS You Have To Follow: Expand 'MyStoremgr' Node Under 'MyStore' Project In Package Explorer. Right Click> Pop Up Menu. Go to Lomboz J2EE> Generate EJB Classes.

Add Callback Methods:

In Contrast to the Stateless Bean, The Ejbcreate Method Will Have AN Argument. This Will Be Used To Initialize a Persistent Field in The Bean.

Add That Field, And Add Accessor and Muttor Methods to Access That Field As Shown Below.

Public Abstract Class StoreAccessStateBean Implements SessionBean {

Private string userid; / **

* @ ejb.interface-method

* View-type = "remote"

* /

Public void setUserid (String UserID) {

THIS.USERID = UserId;

}

/ **

* @ ejb.interface-method

* View-type = "remote"

* /

Public string getUserid () {

Return UserId;

}

Now Add the Ejbcreate Method with the signaturepublic void ejbcreate (String UserID)

Assign Userid to The Persistent Field Userid We create Above as shown.

Now, The Other Two Callback Methods Required To Complete this Bean Are

SetSessionContext.

2. UnsetSessionContext.

Add a field to store sessioncontext.

Protected sessionContext CTX;

Add A Method SetSessionContext with sessioncontext as its parameter and assign That to the sessioncontext variable as shown below.

SIMILARLY, ADD A Method UnsetSessionContext Which Sets The Context Variable To Null As Shown Above.

Note:. The StoreAccessStateSession class inherits the StoreAccessStateBean abstract class and implements SessionBean, which will override all methods of the interface SessionBean So, after completing the methods in your bean class, generate your EJB classes again The SessionContext methods will be overridden, as discussed. In previous chapter.

Generate EJB Classes.

Note: The Steps to Generate The EJB Classes Are Discussed Above and in The Previous Chapter CHAPTER.

Implement Dao Interface:

WE Don't have to import the dao interface as we are using the storeAccessdaoImpl class create

So Go Into The StoreAccessDaoImpl Class and Change The Class Declaration Statement, So That IT IT IT IT IT ITEMENTS StoreAccessStatedao Interface, AS Shown Below In Code Snippet.

Now, All Methods Are IMplement, And Only Deployment Descriptors Remain To Be Done.Deploy Bean:

IN Order to Deployur Bean We Have to Declare A Few Tags in StoreAccessStateBean Class As Shown Below.

Add The Tag Shown Below In StoreAccessStateBean At Class Level (at the top).

@ ejb.resource-ref res-ref-name = "jdbc / defaultds"

Res-Type = "javax.sql.datasource"

Res-auth = "container"

THIS TAG WILL Generate Deployment Descriptors in EJB-JAR.XML, AS The Bean Has To Know Which Datasource You are Going to Connect, What Is ITS TYPE, ETC. This Will Generate these Descriptors As Shown Below.

Add this Tag Shown Below In StoreAccessStateBean At Class Level (At top).

@ JBoss.Resource-ref res-name = "jdbc / defaultds" jndi-name = "java: / defaultds"

THIS TAG WILL Generate Deployment Descriptors in jboss.xml, As the application Server Has To Know with what jndi-name the Datasource Has Been Registered with. This Will Generate The Descriptors as shown Below.

Add this Tag Shown Below In StoreAccessStateBean At Class Level (At top).

@ jboss.container-configuration name = "Standard Stateful SessionBean"

This tag will generate deployment descriptors in jboss.xml, as the application server has to know which configuartion is to be read for Stateful Bean from standardjboss.xml under /opt/jboss/jboss-3.2.1/server/all/conf/. This Will Generate The Descriptors in jboss.xml as shown bellow.

StoreAccessState

StoreAccessStateBean

Standard Stateful SessionBean

jdbc / defaultds java: / defaultds

Note: This configuration is for container in Jboss to read for Stateful Session Bean Jboss comes with timeout of 60 mins for stateful session bean Change the attribute to 120 secs.. (I: e2 mins) and restart your Server As Shown Below In Code Snippet from /opt/jboss/jboss-3.2.1/servaer/all/conf/standardjboss.xml.

Standard Stateful SessionBean

False

stateful-rmi-infoker

-------------------------------------------------- -----------------

-------------------------------------------------- --------------------

-------------------------------------------------- -------------------

Org.jboss.ejb.plugins.lrustatefulContextCachepolicy

50

1000000

1800

120

120

TO 120 SECS (2 mins) And Restart The Server to Read this config.

->

1800

300

600

400 60

1

0.75

-------------------------------------------------- --------------------

-------------------------------------------------- -------------------

Now, Everything is Complete, And It's Time To Deploy The Bean.

First, Regenerate Your EJB CLASSES SHOWN The Steps Above for the final time.

Note:.. We have regenerated the classes again and again in order to explain every step and its result Once you are familiar with these steps you will only need to generate your classes a few times as you go Either way, it does not affect Your Implementation, SO You CAN (RE) Generate Your Classes However You Prefer to Work.

Go to Lomboz J2EE View> Expand Node MyStore> Expand MyStoremgr> SELECT 'JBOSS 3.2.1 All'.

Right Click> SELECT 'DEBUG Sever' on The Pop Up Menu.

Go to MyStoremgr Node in Lombozj2ee View> Right Click> SELECT Deploy on the pop up menu.

NOTE: THESE Steps Are Covered In The Previous Chapter.

And now Wait for your deployment results.

IF everything goes fine, you will have this message under your console as shown below.

So, Now Your Bean IS Deployed Success, Let's Create A Test Client, Which Will Invoke The Loginuser Method on StoreAccessStateBean.

Create Your Test Client:

Go to Project MyStore Node> SELECT SRC NODE> Right Click.

Select New On POP Up Menu> Select Lomboz EJB Test Client Wizard As Shown Below.

Select package name au.com.tusc.client, with name SessionStateClient and select Ejb Home as au.com.tusc.sessionState.StoreAccessStateHome and Ejb Interface as au.com.tusc.sessionState.StoreAccessState as shown below.This will generate the necessary Helper methods for you in your sessionStateclient class and you simply have to invoke the loginuser method on

SO Add The Lines of Code Shown Below in The TestBean Method.

Public void testbean () {

String userid = NULL;

Try {

au.com.tusc.sessionState.StoreAccessState mybean =

gethome (). Create (userID);

// --------------------------------------

// this is the place you make your caver

//System.out.println (MyBean.callyourthod ());

System.out.println ("Request from Cliant:");

Userid = MyBean.loginuser ("Andy", "passwd");

System.out.println ("Reply from Server: Your Userid IS" UserID;

MyBean.setUserid (userID);

System.out.println ("Going to Sleep for 1 min .....................");

Thread.sleep (60000); // Sleep for 1 minute.

System.out.println ("reply from bean ready 1min mybean.getuserid ());

System.out.println ("Again Going to Sleep for 3 min .......................");

Thread.sleep (180000); // Sleep for 3 minute.

System.out.println ("Resuming After 3 mins .......................");

// Next Statement Will Not Be Executed As Bean Will Timeout on The Server Side

// Resulting in Exception.

System.out.println ("Reply from Bean After 2mins" myBean.getUserid ());

} catch (interruptedexception e) {

} catch (nosuchobjectException e) {

System.out.Println ("No Such Object Exception Caught");

} catch (remoteException E) {

System.out.println ("Remote Exception Caught");} catch (createException e) {

E.PrintStackTrace ();

} catch (namingexception e) {

E.PrintStackTrace ();

} catch (ejbexception e) {

System.out.println ("EJB Exception Caught");

}

}

Public static void main (String [] args) {

SessionStateClient test = new sessionStateClient ();

Test.TestBean ();

}

Test Your Client:

Now, in Order to Test your client, Select SessionStateClient Node> Go at top level menu and select the icon with the 'man running'.

On That Select 'Run as'> Select 'Java Application'.

Now Under Your Console, if you get your reply for 'Andy' as 'u2', EventAfter 1 min But After 3 mins NosuchobjectException is Caught The Your Stateful Bean Is Successful As Shown Below.

Note: SO Our stateful session bean is deployed and ted successfully. This particular bean is not buy again in this tutorial.

转载请注明原文地址:https://www.9cbs.com/read-121914.html

New Post(0)