Tutorial for building J2EE Applications using JBOSS and ECLIPSE(3)

本文介绍如何创建无状态会话EJB组件。该组件通过DAO与数据库通信以实现用户认证,包含创建J2EE项目、无状态Bean、DAO接口等步骤,还涉及添加业务和回调方法、部署Bean、创建并测试客户端等操作,使用Lomboz工具辅助开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Chapter 3.

blurulr6.gif

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) and behavior (methods) corresponding to the bean it is being used for.



J2EECaseStudyFlowDiagram.png


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 :

  1. Create a J2EE project named MyStore.

  2. Create a Stateless Session Bean named StoreAccess.

  3. Add a business method in bean named loginUser with the following signature

    public String loginUser (String username, String password)

  4. Create a DAO named StoreAccessDAOImpl under package au.com.tusc.dao. Generate the DAO interface.

  5. Implement the method named loginUser, generated in DAO interface, in StoreAccessDAOImpl. Method signature is

    public String loginUser (String username, String password)

  6. Add callback methods and implement them.

  7. Deploy StoreAccess bean.

  8. Create your test client named SessionClient under package au.com.tusc.client.

  9. 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.

CreateJ2eeProjectLibraries.png


Under Create J2EE Module, select Web Modules tab > Add.., enter Module name as OnlineStore > OK as shown in figure below.

CreateJ2eeAddWebModule.png


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.

SessionBeanView.png


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 once you generate your EJB classes, which is covered later on in this chapter.

StoreAccessBeanJndiDescp.png


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.

SessionBeanGeneartedDescView.png


Now we are going to generate all the interfaces 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 we 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.



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 <dao> tag specifying the destination directory for the generated DAO interface and what pattern to be used.

ejbGenerateWithDAOView.png
Note : For details, please refer ejbdoclet under Xdoclet documentation.



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 cannot 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 a DAO to access the database for this Stateless Bean, we have to create a DAOImpl class which will implement that generated DAO interface.

Go to src > add package named au.com.tusc.dao > Add a class StoreAccessDAOImpl in that package.

StoreAccessDAOImpl.png


Now go to your Bean class and declare this tag at the class level (that is at the top) as shown below to generate the DAO interface.



StoreAccessBeanDAOTag.png

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.

AddEJBToModule.png

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.

GenerateEJBClassesNow.png

This tag also generates the following descriptors in jboss.xml as shown in the code snippet below.

jboss.png
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 in the bean.

Go to StoreAccesBean > Right click > Select New on pop up menu > Select Lomboz Ejb Method Wizard.

CreateEJBMethod.png

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..

AddBusinessBMethod.png

This wizard generates a loginUser method in our bean class, with the method level tag '@ejb.interface' shown below.

SessionBeanInterfaceTag.png

This tag is responsible for generating this method in the Remote Interface (in this case it is StoreAccess which will be created once you generate your classes). This tag is covered later on in this chapter.


After generating the classes, we look at first the generated DAO interface and then the generated Session Class.

In StoreAcessDAO two methods are generated.

1. init() by default.

2. loginUser(), generated by tag shown below.


StoreAccessDAO.png
Note: Please do not edit any class generated by Xdoclect.

In StoreAcessSession two methods of our interest are

1. getDAO() creates instance of DAOImpl calss.

2. loginUser(), calls loginUser method in DAOImpl class, which we have to implement.

Code snippet from 'StoreAccessSession'.

StoreAccessSession.png


Implement DAO Interface :

Now, we will implement methods in the StoreAccessDAOImpl class.

In StoreAcessBean class under the loginUser method just add some debug statements, as shown below in this code snippet.

StoreAccessBeanLoginUser.png
Note : We don't 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.

StoreAccessSessionLoginUser.png


Add Callback Methods :

Now, add callback methods to complete this bean as shown below.

  1. setSessionContext.

  2. UnsetSessionContext.

Note : These 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.

StoreAccessBean.png
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.

StoreAccessSessionContextMethods.png


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.

SessionBeanInterfaceTag.png


So, loginUser is generated in a Remote Interface called StoreAccess as shown below because of this tag.

SessionBeanRemoteInterface.png


In the case of the Home Interface only one method is created named 'create', which is generated by default because of the <homeinterface/> tag in ejbGenerate.xml as shown below.

SessionBeanHome.png


Also, other then that, it has JNDI_NAME and COMP_NAME (which is the logical name to lookup the component) is also generated, these are generated because of this tag declared at class level in 'StoreAccessBean' class shown below in figure.

StoreAccessBeanJndiDescp.png
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 :


In order to deploy our bean we have to declare a few tags in the StoreAccessBean class as shown below in the code snippet.

StoreAccessBeanAllDescriptors.png


Add the tag shown below in at the class level (at the top).


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.

ejb-jarResourceRef.png


Add the tag shown below in StoreAccessBean at the class level (at the top).


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.

jbossResourceRef..png


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 iterations. 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.

LombozJ2EEDebugServer.png


Go to MyStoreMgr node in LombozJ2EE view > right click > select Deploy on the pop up menu as shown in the figure below.

LombozJ2EEDeploy.png


And now wait for your deployment result.

If everything goes fine, you will have this message under your console as shown in the figure below.

LombozJ2EEBeanDeployed.png


So, now our bean is deployed successfully, 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 below.

CreateEJBTestClient.png


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.

CreateEJBTestClientPackageName.png


This will generate the required methods for you in your SessionClient class and you have to just invoke the loginUser method on the bean as shown below.

SessionCleint.png


Now the last step is to write code in your client.

So add these lines under the testBean method as shown in figure below.



SessionCleintAddLoginUser.png


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.

RunSessionClient.png


Now under your console, if you get your reply for 'ANDY' as 'U2', then your call is successful as shown below.

TestClient'sResult.png


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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值