Chapter 3.
Creating a stateless session bean
This chapter covers how to create a stateless session EJB component. This bean will be responsible for authenticating the user by communicating with the database using Data Access Object (DAO) which encapsulates Java Database Connectivity (JDBC) code. A DAO has all attributes (fields ) Corresponding to the bean it is being used for.
All customers, supplier and manager of MyStore have been assigned a unique username and userid to access services of MyStore, but in order to access these services all these entities have to first login into the system (MyStore). The method for authentication is named loginUser Which Takes Two String Parameters, UserName and Password And Returns The Userid IF Authentication Is Successful.
Note: This method loginUser is a business method, normally business methods carry out operations or processing on values EJB components From clients perspective, clients can see only business methods and invoke them on bean..
Tasks:
Create a J2EE project named MyStore. Create a Stateless Session Bean named StoreAccess. Add a business method in bean named loginUser with the following signature public String loginUser (String username, String password) Create a DAO named StoreAccessDAOImpl under package au.com.tusc. dao. Generate the DAO interface. Implement the method named loginUser, generated in DAO interface, in StoreAccessDAOImpl. Method signature is public String loginUser (String username, String password) Add callback methods and implement them. Deploy StoreAccess bean. Create your test client named SESSIONCLIENT Under Package Au.com.Tusc.Client. Run Your Client and Test The Bean.
Create J2ee Project:
Now, Lets Start to Write Our First Component of this Tutorial.go to File> New> Lombozj2ee Project, Project Creation Wizard Will Pop Up.
Insert Project Name MyStore> Next.
Under Java Settings Check Source, Should Be MyStore / Src, Libraries Pointing to $ Java_Home> Go Next As Shown in Fig Below.
Note: This Step is shown in chapter1, as there is a bug in Eclipse 2.1, SO ITS Important That You Check your library settings are right.
Under Create J2EE Module, Select Web Modules Tab> Add .., Enter Module Name as OnlineStore> OK As Shown In Figure Below.
Under Create J2EE Module, Select EJB Modules Tab> Add .., Enter Module Name as MyStoremgr> OK.
Under Create J2EE Module, Select Targeted Servers Tab> Select JBoss 3.2.1 All> add ..> finish.
Create Stateless Bean:
Go to Package Explorer> Expand MyStore (Project) Node> SELECT SRC, RIGHT CLICK AND MENU WILL POP UP.
On pop up menu> New> Lomboz EJB CREATION WIZARD.
Enter package name au.com.tusc.session, Bean name storeAccess and select bean type as stateless> finish.
This Will Create a package named au.com.tusc.session under src and storeaccessBean Under That Package As Shown In The Figure Below.
As we can see from the figure below 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 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 the file Also, the name of file is appended with word 'Bean' as you gave the name of the bean as StoreAccess only Again, be careful with naming conventions, specifying the bean name only in the wizard without adding the word 'bean' to the name as the wizard appends that for you.Expand MyStoreMgr / META-INF node under Package Explorer. You will find there are seven files which are generated By Lomboz Using Xdoclet as Shown in The Figure. BELOW.
NOW Weaves Including Home, Remote, Dao and Other Helper Classes. We Will Explain Why Later ON, But for The Time Being Just Follow The Steps.
But Before Get Too Excited, There Are A Few Concepts to Cover Here.
Go to myStoremgr / Meta-inf> select and open ejbgenerate.xml.
Note: Lomboz uses this file to generate required interfaces and helper classes, so in the event that you have special needs then you will have to customize this file See ejbdoclet under the Xdoclet documentation..
'EJBGENERATE.XML' File Is Generated Only Once WHEN You Create Your Ejb Module. So Any Changes Made In this File Will Be Reflected Even IF You Modify Your Bean Class and Generate Your Classes Again and Again.
As we can see from the code snippet of file shown in figure at right, there are following tags defined.
The other two files which are of importance to us are ejb-jar.xml and jboss.xml. The file ejb-jar.xml has all the deployment descriptors for beans and jboss.xml has the JBOSS specific deployment descriptors required by JBOSS.Note : ejb-jar.xml file is generated every time you generate interface and helper classes for your bean for the first time, it is empty, and jboss.xml will be generated every time when you will generate your classes for your bean..
Setup Dao:
Now, Let's Customize EJBGENERATE.XML for Setting Up A DAO.
WE HAVE INCLUDED A
NOTE: for Details, please refer ejbdoclet under xdoclet documentation.
We have included the datasource, datasoucremapping and preferredrelationmapping as shown in code snippet of ejbGenerate.xml file on right datasource =. "Java: / DefaultDS" is a local JNDI name for data source to be used datsourcemapping = "Hypersonic SQL" maps data. . object / value objects and their types to columns and data types associated with these columns preferredrelationmapping = "foreign-key" defines type of database to be used Note:. For more details, please refer JBOSS documentation Since we are using the Hypersonic database. , these parameters are appropriate to that. These parameters relate to the configuration file standardjbosscmp-jdbc.xml which controls the CMP-to-JDBC mappings for JBOSS. This resides in $ JBOSS_HOME / server / conf /, eg / opt / jboss / jboss -3.2.1 / Server / Default / conf /. Code snippet from standardjbosscmp-jdbc.xml is shown in Figure at right.
Note: The way Xdoclet works is bit different from some conventional styles of programming, as the Xdoclet tags will generate these (home and remote) interfaces along with necessary helper classes, which then will used in Bean and DAO Implementation class However, until these. are generated, we can not write any business methods in Bean and JDBC wrappers in the DAO Implementation class If this seems confusing then just follow the steps, and hopefully it will become more clear.Create DAO Interface.:
Since We are going to use.
Go to SRC> Add package named a class storeage.
Now Go To your bean class and declare this tag at the class belove (That is at the top) as shown Below To Generate The Dao Interface.
@ ejb.dao class = "au.com.tusc.session.storeAccessDao"
Impl-class = "au.com.tusc.dao.storeAccessdaoImpl"
EXPAND StoreAccessBean 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.
Expand MyStoremgr Node Under MyStore Project In Package Explorer. Right Click and A Menu Will Pop Up.
Go to Lomboz J2EE> Generate EJB CLASSES As Shown In The Figure Below.
EJB interfaces and helper classes are generated under ejbsrc / au.com.tusc.session directory as shown in the figure at the right. Seven files are generated. StoreAccess is the remote object interface. StoreAccessLocal is the local object interface. StoreAccessSession extends our bean class named StoreAccesBean. StoreAccessHome is the remote home interface. StoreAccessLocalHome is the local home interface. StoreAccessUtil is a helper class which has methods for accessing Home and LocalHome interface along with generating GUID. StoreAccesDAO is the DAO interface which we will use to implement our StoreAccessDAOImpl Under au.com.tusc.dao. StoreAccessdao is generated by this Tag Declared in StoreRedSbean Shown Below. if you don't declare this tag in That File It Won't generate this interface. @ Ejb.dao class = au.com. Tusc.Session.StoreAccessDaoImpl-class = au.com.tusc.dao.storeAccessDaoImpl Other Files of Interest Which AretribrGR / Meta-infaults.
As shown in the figure on the right, a few descriptors are generated in the ejb-jar.xml file. These descriptors are generated by the following tag declared in the StoreAccesBean file. @ Ejb.bean name = "StoreAccess"
JNDI-Name = "StoreAccessBean"
TYPE = "stateless" this tag is added by Lomboz's bean creeion wizard.
THIS TAG Also Genereates The Following Descriptors in Jboss.xml As Shown In The Code Snippet Below.
SO NOW WE KNOW WHICH TAGS Are Responsible for Generating Classes, Interfaces and Descriptors.
Add Business Method:
Next Step is to add a business method.
Go to StoreAccesBean> Right click> Select New on pop up menu> Select Lomboz Ejb Method Wizard.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 In The Figure 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 is the store you generate your classes). This Tag is Covered Later ON This Chapter.
Now, This business method needs to invoke a method on the DAO, which will communicate with the database. Therefore we add another tag on this method, so that a method with this signature is generated in DAO interface which we can implement in the DAOImpl class . Then this business method can invoke the method in DAOImpl class to get the desired result. @ dao.call name = "loginUser" So add this tag at the method level as shown in the figure at right. Now generate your EJB classes again as shown in the steps we went through earlier Note:. OK, OK For reference these are the steps you have to follow 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.
After Generating The Classes, WE Look At First The Generated Dao Interface and The Generated Session Class.
In StoreacessDao Two Methods Are Generated.
INIT () by Default.
2. Loginuser (), generated by tag shown below.
@ dao.call name = "loginuser"
Note: please do not edit any class generated by xdoclect.in storeacesssession Two Methods of Our Interest Are
GetDao () Creates Instance of DaoIMPL CALSS.
2. Loginuser (), Calls Loginuser Method in DaoIMPL Class, Which We Have to Implement.
Code Snippet from 'StoreAccessSession'.
Implement Dao Interface:
Now, We will Implement Methods in The StoreAccessDaoImpl Class.
First import the following packages javax.naming.InitialContext;. Javax.sql.DataSource; java.sql.Connection; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; Change your class declaration so that StoreAccessDAOImpl implements .. StoreAccessDAO Add a field to store the JDBC resource factory reference private DataSource jdbcFactory; in init () method, locate the reference "jdbc / DefaultDS" using the JNDI API, and store the reference in variable jdbcFactory Lookup string is "java:. COMP / ENV / JDBC / Defaultds ". Code Snippet is Shown In The Figure, on the right. Now add the required code in loginuser ().
In method loginUser (), first get the connection to the database using the jdbcFactory. Create a SQL statement which searches for userid in the table StoreAccess where userid and password is provided for each user. Return userid if successful, else raise SQLException. Code snippet IS Shown in The Figure Loginuser Method in StoreAccessBean Class.
In StoreacessBean Class Under The LoginUser Method Just Add Some Debug Statements, AS Shown Below In this code snippet.
Note: We do not have to call the loginUser method in StoreAccessDAOImpl, as it being invoked by the loginUser method in StoreAccessSession class which inherits StoreAccessBean class, that is the StoreAccessSession class has overridden this method.Code snippet from StoreAccessSession shown below.
Add Callback Methods:
Now, Add Callback Methods to Complete this bean as shown below.
SetSessionContext. unsetSessionContext.
NOTE: The Callback Methods Are Invoked by The EJB Container.
Add a field to store sessioncontext.
Protected sessionContext CTX;
Add Method SetSessionContext with sessioncontext as parameter and assign That to the sessioncontext variable as shown Below in the code snippet.
SIMILARLY Add Method UnsetSessionContext, Assign Context variable to null as shown above.
Note:.. StoreAccessSession class inherits the StoreAccessBean abstract class and implements SessionBean, which will override all methods of interface SessionBean So after finishing the methods in the bean class, generate your EJB classes again SessionContext methods will be overridden as shown in figure below Code. Snippet from StoreAccessSession Shown Below.
Now Let's Look At The Generated Home and Remote Interfaces.
In the case of the Remote interface all business methods declared in the bean are also generated with the same signature. This is due to the class level tag declared in the StoreAccess Bean as discussed above after adding business methods. Code snippet for tag is shown below .
SO, Loginuser is Generated in a Remote Interface Called StoreAccess As Shown Below BECAUSE OF THIS TAG.
In the case of the Home Interface only one method is created named 'create', which is generated by default because of the
Note: for further options associated with these tags please refer to the 'ejbdoclet' documentation in xdoclet.
Now, All The Aspects Are Pretty Much Covered, And Our Bean's FunctionAlity Is Complete. Now for the deployment descriptors ..
Deploy bean:
.
Add The Tag Shown Below In At The 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 to, what is its type, etc. This will generate these descriptors as shown in code snippet below.
Add The Tag Shown Below In StoreAccessBean At The Class Level (At the 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 datasource it has been registered with. This will generate these descriptors as shown in the code snippet below.
Now, Everything is Complete, And It's Time To Deploy The Bean.
First, regenerate your EJB classes as shown in 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 need much fewer Of these iterates. Either Way, IT Doesn't Matter, As Your Implementation Always Remains Untouched by this process.
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 As Shown in Figure Below.
Go to MyStoremgr Node in Lombozj2ee View> Right Click> Select Deploy on the pop up menu as shown in The first Below.
And now Wait for your deployment results.
If He Will Have this Message Under Your Console As Shown In The Figure Below.
So, Now Our Bean is deployed successful, let's create our test client, Which Will Invoke The Loginuser Method On 'StoreAccessBean'.
Create Your Test Client:
Go to Project MytStore Node> SELECT SRC NODE> Right Click.
Select New On POP Up Menu> Select Lomboz EJB Test Client Wizard As Shown in The Figure Figure Below.
Select package name au.com.tusc.client, name as SessionClient and select Ejb Home as au.com.tusc.session.StoreAccessHome and Ejb Interface as au.com.tusc.session.StoreAccess as shown in the figure below.
........................... ...CRIPLITAverabna, THE, TOE
Now The last step is to write code in your client.
SO Add these Lines Under The TestBean Method As Shown in Figure Below.
System.out.println ("Request from Cliant:");
System.out.Println ("Reply from Server: Your Userid IS" MyBean.loginuser ("Andy", "Passwd"));
Test Your Client:
Now, in Order to Test Your Client, Select SessionClient Node> Go At Top Level Menu and Select The icon with the 'Running Man'.
On That Select 'Run As'> Select 'Java Application', AS Shown Below.
Now Under Your Console, if you get your reply for 'andy' as 'u2', The Your Call Is Successful As Shown Below.
Note:. So our Stateless Session Bean is deployed and tested successfully and from now onwards you should be comfortable using Lomboz In future we will not go into the detail of the steps for using Lomboz and will concentrate more on other aspects of beans.