This application will take you through the basics of Stateful Session Bean. This application will demonstrate how annotations like @Stateful, @Resource, @PostConstruct, @PreDestroy, @PrePassivate, @PostActivate, @Remove are used in an EJB3 application.
Basically a Stateful Session EJB is used whenever there is a requirement to maintain a session. The example is a user registration process wherein the registration process is a two step process. First page prompts to enter your personal credentials and second page prompts to enter your billing and credit card information. The session is maintained till the user has filled up both the jsp pages. Later the complete information is populated on to a database. The application has a Controller servlet which routes the call received from the jsp client to the Bean class, setter methods and jsp pages.
To run this tutorial, as a minimum you will be required to have installed the following prerequisite software.
- Sun JDK 5.0+ (J2SE 1.5)
- Eclipse 188.8.131.52 (Eclipse Classic package of Europa distribution), which is platform specific
- Web Tools Platform (WTP) 2.0.1
- Data Tools Platform (DTP) 1.5.1
- Eclipse Modeling Framework (EMF) 2.3.1
- Graphical Editing Framework (GEF) 3.3.1
Details on installing eclipse are provided in the Development environment section.
This tutorial is organized in the following sections:
Creating an EJB project
This section is organized in the following parts:
Setting up the project environment
- Right click Under Project Explorer and Select New->EJB Project.
- Name the project as StatefulBean. Select Next.
- Mark the fields as suggested in the screenshot and Select Next.
- Uncheck Generate Deployment Descriptor. This is beacuse we are using annotations is our applications and so deployment descriptors are redundant entity. Select Next.
- On next screen select all default values and Select Finish.
This creates a skeleton for the EJB project. Next steps are adding the bean class, bean interface and setter/getter methods.
- Right click on ejbModule in StatefulBean project and select New->class.
- Name the class as PersonalInfo and package as ejb.stateful. Select Finish.
Adding Java classes and interfaces
- Add the following code to
- Similarly create a class
BillingInfo.java and add the following code.
BillingInfo.java are classes for setting and getting the user information.
- Now we will add the Business interface or bean interface. Right click on the package ejb.stateful and Select New->Interface.
- Name the interface as AccountCreator and Select Finish.
- Add the following code to AccountCreator interface.
Note: Once you enter this code you might see errors like @EJB can be resolved. Currently there are some limitations with the geronimo eclipse plugin which will resolved soon. We will soon suggest you how to get rid of those errors.
- Next step is to add the implementation to the interface. Right click on ejb.stateful interface and select New->class.
- Name the bean class as AccountCreatorBean and Select Finish.
- Add the following code to AccountCreatorBean.
Once you have added the code you will see lot of errors but this can be resolved easily and is shown in next step. The errors in the code is due to missing classes from our server runtime.
Making additional configurations
Resolve the errors as follows.
- Right click on StatefulBean project and select Properties.
- On the next screen select Java Build Path->Libraries->Add External Jars.
- Browse to
<GERONIMO_HOME>/repository/org/apache/geronimo/specs/geronimo-ejb_3.0_spec/1.0.1 and select geronimo-ejb_3.0_spec-1.0.1.jar. Select Open.
- Similarly browse to <GERONIMO_HOME>/repository/org/apache/geronimo/specs/geronimo-annotation_1.0_spec/1.1.1 and add
- Once done you can see both the jars enlisted. Select OK.
Let us walk through the EJB bean class code.
- @Stateful public class AccountCreatorBean implements AccountCreator- @ Stateful annotation declares the Bean class as Stateful class.
- @Resource(name="jdbc/userds") DataSource datasource;- This is a resource injection into the bean class wherin a datasource is injected using the @Resource annotation. We will shortly see how to create a datasource in geronimo.
- public AccountCreatorBean*-This is a constructor for the bean class and it will be used to create a bean instance whenever a request is received from new client connection.
- @PostConstruct, @PostActivate public void openConnection()- @PostConstruct and @PostActivate are annotations which are basically called lifecycle callback annotation. The lifecycle for these annotation is as follows
- New bean instance is created using the default constructor.
- Resources are injected
- Now the PostConstruct method is called which in our case is to open a database connection.
- PostActivate is called on the bean instances which have been passivated and required to be reactivated. It goes on the same cycle as being followed by PostConstruct.
- @PreDestroy @PrePassivate public void closeConnection()- Again @PreDestroy and @PrePassivate are Lifecycle callback annotation. The lifecycle of these annotation is as follows
- Bean instances in the pool are used and business methods are invoked.
- Once the client is idle for a period of time container passivates the bean instance. The closeConnection function is called just before container passivates the bean.
- If the client does not invoke a passivated bean for a period of time it is destroyed.
- public void addPersonalInfo(PersonalInfo personalinfo) and public void addBillingInfo(BillingInfo billinginfo)- These two functions are invoked to store client data across various calls.
- @Remove public void createAccount()- There are two ways in which a bean is destroyed and hence this where a client session ends in stateful bean. One is when a bean has been passivated and is not reinvoked by client hence the bean instance is destroyed. Another way is to use @Remove annotation. Once the client confirms and submits all the required information the data is populated into the database and that is where the session ends.
Creating a database using the administrative console
- Start the server and lunch the administrative console using the URL http://localhost:8080/console.
- Enter default username and password.
- In the welcome page, Under Embedded DB, Select DB Manager.
- On the next page create a database named userdbs and Select Create.
- Once done you can see the userdbs database listed in DB Viewer portlet under Databases. This confirms that the database has been successfully created.
- As shown in the figure under Use DB, select userdbs from the dropdown box.
- Run the
userinfo.sql script. Select Run Sql.
- To verify the table creation succeeded. Select Application as shown in the figure.
- Next screen suggests the table has been successfully created. To view the contents of the table select VIEW CONTENTS.
- The table is currently empty as shown in the figure.
Creating a datasource using the administrative console
- Start the server and launch the administrative console using the URL http://localhost:8080/console.
- Enter default username and password.
- Once in the welcome page. In console navigation, Under Services, Select Database Pools.
- On the next screen, Create a new database pool using Geronimo database pool wizard.
- On the next screen give the name as suggested in the figure. This will initiate the process to create a Derby Embedded XA datasource.
- Select the Driver jar and give the database name as userdbs (Remember this is the database we created in the previous step). Rest all fields can be set to default.
- Select Deploy to deploy the connector plan.
- Once done you can see the Database Pool jdbc/userds listed in the available database pools.
Creating a Web based application client
- Right click under Project Explorer and Select New->Dynamic Web Project.
- Name the project as StatefulClient and Select Next.
- Keep the default settings as shown in the figure. Select Next.
- On the next screen keep default values. Select Next.
- Default values on this screen too. Select Finish.
- Right click on the StatefulClient project and Select New->Servlet.
- Name the package as ejb.stateful and Servlet as Controller.
- Keep the default values and Select Next.
- Keep the default values and Select Finish.
- Once the servlet is created it shows error. This is due to servlet api missing from the runtime. This can be easily resolved. Right click on StatefulClient project and Select Properties.
- On the next screen select Java build path and select Libraries.
- Select Add External jars.
- Browse to your
<GERONIMO_HOME>\repository\org\apache\geronimo\specs\geronimo-servlet_2.5_spec\1.1.2 and select geronimo-servlet_2.5_spec-1.1.2.jar and Select Open.
- Select OK on the next screen this will remove all the errors.
- Add the following code to
This servlet contains code referring to bean interface class and PersonalInfo and BilllingInfo class. We need to add these projects to the build path so that the classes can be compiled.
- Right click on StatefulClient project and Select Properties->Java Build Path->Projects. Select Add.
- Check StatefulBean and Select OK.
- Once done the project will be visible in the build path. Select OK.
- Next step is to add jsp pages to our client project. Right click on WebContent under StatefulClient project and Select New->jsp.
- Name the jsp as
PersonalInfo.jsp and Select Next.
- On the next screen select Finish.
- Add the following code to
- Similarly add another jsp with the name
BillingInfo.jsp and add the following code.
Let's walk through the servlet and jsp code. First through Controller servlet code.
- if ( (request.getRequestURI()).equals("/StatefulClient/Controller"))- This code act as a controller on the jsp which is making a request. This is possible only when the jsp's make a call to th servlet with different names. How this can be done will be illustrated in the next section.
- HttpSession hs= request.getSession(true); hs.setAttribute("handle", ac); This part of the code saves the remote interface handle and later in the second call same handle is used to make another call to bean methods.
- RequestDispatcher rd=request.getRequestDispatcher("BillingInfo.jsp")- This code section and the next line forwards the control to next jsp that is BillingInfo.jsp.
- Rest of the servlet deals with calling the setter methods and later sets the object so as to persist the data between different calls.
- Next walkthrough the jsp code.
- PersonalInfo.jsp has <form action="Controller"> whereas BillingInfo.jsp has <form action="Controller1"> as the action element but both internally calling the same servlet. This can be easily done by modifying web.xml this will be shown in the next section.
Modifying openejb-jar.xml, web.xml and geronimo-web.xml
- In StatefulBean project select META-INF/openejb-jar.xml and replace the existing code with following code
The above deployment plan is different from the above one in the following way
- The namespace generated by geronimo eclipse plugin are not to AG 2.1 level. This is due to some limitation which will be fixed soon.
- Since the ejb bean class refers to jdbc/userds datasource a <dependency> element has to be added in EJB deployment plan.
- In StatefulClient project select WEB-INF/web.xml and replace the existing code with the following
- In StatefulClient project select WEB-INF/geronimo-web.xml and add a dependency element for the StatefulBean EJB project. THe final web deployment plan will look as follows
The above code is different from the original one in the sense that we have added another <servlet> for Controller1 which is mapped to the same servlet class. Similarly adding a <servlet-mapping> element for the Controller1 servlet. This feature is basically mapping of more than one servlet with same servlet class. This helps in routing each call from jsp in the Controller servlet.
Deploy and Run
- Under project explorer right click on StatefulBean project and select Export->EJB jar file.
- Browse to a destination and Select Finish.
- Similarly export StatefulClient project.
- Launch the administrative console with http://localhost:8080/console. Under application select Deploy New.
- Browse to the StatefulBean project and select Install.
- Similarly deploy StatefulClient project.
- Launch the application using the link http://localhost:8080/StatefulClient/PersonalInfo.jsp. Fill up the form and select SubmitQuery.
- Once you submitt the current page, next page will be displayed wherein you need to enter your Billing Information. Once done select SubmitQuery.
- Later you can verify the database which is populated with the user data.