How to create an EJB3 (Statefull Session Beans) in Eclipse Europa
Again I am here to talk about EJB3. In this topic I am going to cover the creating of an EJB3 (Statefull Session Beans) in Eclipse Europa.
This topic is going to be similar than this one: http://www.jairrillo.com/blog/2008/04/25/example-of-ejb3-session-bean-using-eclipse-europa-and-jboss/, except by the fact that this topic will cover Statefull session bean rather than Stateless Session Beans.
The big difference between them, it the statefull session beans keeps a state among different requests as long as stateless session beans loss the state when the request dies.
Hence, statefull sessions beans could be used when you need to keep a state, for instance, a cart object in an e-commerce application. Of course there are other differences, but it is the major.
Although statefull sessions beans seems more powerful than stateless, you have to keep in mind that this “power” has a cost to the server. When you are using a statefull session beans, the server must store them in any way. Hence, you must think well if you really need the Statefull instead Stateless.
Here, we are going to create a simple application. The session beans component has the responsibility to “count” how many time a certain link is clicked by the SAME user, therefore we need to use Statefull (to keep the state).
I am not going to show you many print-screen, so if you never build an EJB application into Eclipse, I advice you to take a look at the topic shown above.
Creating the project
Within eclipse environment, go to the J2EE perspective (it is the default) and right-click on Project Explorer and go to: New -> Enterprise Application Project. On the new screen, insert the Project name (I’ve used JavaEELesson) and click on Next twice. On third screen, click on New Module and choose the EJB module and Web module. Also, mark the checkbox Generate Deployment Descriptor.
You will see on the Package Explorer three projects: JavaEELesson, JavaEELessonEJB, JavaEELessonWeb.
Implementing the EJB Module
It is time to implement our Statefull Session Bean component. Remember the requirement: “we are going to create a component that counts how many time a certain link is clicked by one user. Even this user goes to other page and back into the same session, the count must be active.”
Of course it is a silly requirement, but it can show us how to create a Statefull component.
Creating the Interface
Like the stateless, we need an interface. Right click on JavaEELessonEJB and go to: New -> Interface. On the new screen insert the Package Name(in my case I’ve used statefull) and then insert the interface name (in my case I’ve used Counter).
We are going to use two methods in this interface: count() that will increase +1 the count object and getCount() that will return the value of the count object. The code looks like below:
package statefull; public interface Counter { public void count(); public int getCount(); }
So far so good!!
Implementing the Interface
Now let’s create a concrete class to implement this interface. Right click on JavaEELessonEJB and go to: New -> Class. On the new screen, insert the package (statefull), name (CounterBean) and select the Counter interface.
The implementation of this class looks like below:
package statefull; import java.io.Serializable; import javax.ejb.Remote; import javax.ejb.Stateful; @Stateful @Remote(Counter.class) public class CounterBean implements Counter, Serializable { private static final long serialVersionUID = 1L; private int count; public void count() { this.count++; } public int getCount() { return this.count; } }
Pay attention on the code. Look at the @Statefull annotation. Also, pay attention we are implementing the interface Serializable, but why? Because we need to store our object, so the easier way to do that is make our object Serializable. The rest of the code is simple, nothing special.
Our EJB component is done and ready for use.
Creating the Client through a WEB project
It is common a WEB project access the EJB components. If you are using Glassfish, you can simply gets the EJB component though DI using the annotation @EJB (when you are in a Enterprise Environment). If you are JBoss, you must use JNDI (look at the post above that talks about it).
In my case, I am using Glassfish, but you are free to use another Java EE Application Server as well.
Creating the JSP pages
In our project, we are going to create a couple of JSP pages. The first one is the famous index.jsp. It contains a link to a Servlet which calls the Statefull Session Bean and send the result to the result.jsp page. This page though, will show up the value of the counter.
Let’s get started by the index.jsp. Expand the JavaEELessonWeb and right-click on WebContent -> New -> JSP. Insert the file name index.jsp and click on Finish.
The content of the index.jsp page looks like:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Index</title> </head> <body> <h3>JavaEE Lesson Web application</h3> <a href="CounterServlet">Click here to count your click</a> </body> </html>
As you can see, the link calls a servlet called CounterServlet. We are going to implement it soon.
Now repeat the process and create a file called result.jsp. In this file, we are going to print out the result of a variable called counter. Code looks like:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>result</title> </head> <body> <h3>Result</h3> <%= request.getAttribute("counter" ) %><br /> <a href="index.jsp">Back to index page</a> </body> </html>
Nothing special above, huh? There is only a JSP tag to prints out the content of the object counter. Also, there is a link to the user get back to the index.jsp page.
Now it is time to create our Servlet. It’s name is CounterServlet. Right click on JavaEELessonWeb -> New -> Servlet. Insert the package servlets and the name CounterServlet. Click next twice and then uncheck the values: Contructor for Superclass and doPot. (we do not need these methods).
In the CounterServlet we need to call the EJB component. In Glassfish we could use the @EJB annotation. Inside the doGet method, you will call the methods to count the counter (count()) and then store the new counter in a variable (getCount()). Finally we will send the value to the request object and call the result.jsp file. The CounterServlet.java class looks like:
package servlets; import java.io.IOException; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import statefull.Counter; public class CounterServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; private Counter counter; protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { //increase +1 on Count attribute from EJB component counter.count(); //get the current value of the Count attribute Integer count = counter.getCount(); //Send the value to request object request.setAttribute("counter", count); //redirect the page request.getRequestDispatcher("result.jsp").forward(request, response); } @EJB public void setCounter(Counter counter) { this.counter = counter; } }
Now you can run your server (Right click on JavaEELessonWeb and choose your-server). When the index.jsp displays, click on the LINK and you will see the result.jsp priting out 1 (by the first step). Back to the index.jsp page and repeat the process several times. You will see the counter being increased, in other words, our EJB components is keeping its state.
As said, it is a silly application, but it can be useful for who is getting started in the Statefull Session Beans development using Eclipse Europa.

Brazilian guy, IT Specialist, Linux User, IBM Certified SOA Fundamentals, Rational Developer, Sun Certified Java Associate 1.0, Sun Certified Java Programmer 1.4, Sun Certified Web Component Developer 1.4 and Sun Certified Business Component Developer 5. Also Ruby and Python enthusiastic.
Hi
I Follow your steps. But here I m facing following problem. Please guide me.
java.lang.NullPointerException
CounterServlet.doGet(CounterServlet.java:26)
javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
Hay,
I deploy it again after removing .ear file and it works.
I run it successfully. Thank you so much for tutorial.
It’s really great.
Hello Jair,
I have a problem when I start my Application Server(GlassFish).
The description of my problem is bellow.
java.lang.RuntimeException: Could not invoke defineClass!
at com.sun.corba.ee.impl.codegen.CodeGeneratorUtil.makeClass(CodeGeneratorUtil.java:98)
at com.sun.corba.ee.spi.codegen.Wrapper._generate(Wrapper.java:1051)
at com.sun.ejb.EJBUtils.generateAndLoad(EJBUtils.java:589)
at com.sun.ejb.EJBUtils.loadGeneratedRemoteBusinessClasses(EJBUtils.java:485)
at com.sun.ejb.containers.BaseContainer.(BaseContainer.java:507)
at com.sun.ejb.containers.StatefulSessionContainer.(StatefulSessionContainer.java:350)
at com.sun.ejb.containers.builder.StatefulContainerBuilder.createContainer(StatefulContainerBuilder.java:120)
at com.sun.ejb.containers.builder.BaseContainerBuilder.buildContainer(BaseContainerBuilder.java:99)
at com.sun.ejb.containers.ContainerFactoryImpl.createContainer(ContainerFactoryImpl.java:510)
at com.sun.enterprise.server.AbstractLoader.loadEjbs(AbstractLoader.java:536)
at com.sun.enterprise.server.ApplicationLoader.doLoad(ApplicationLoader.java:188)
at com.sun.enterprise.server.TomcatApplicationLoader.doLoad(TomcatApplicationLoader.java:126)
at com.sun.enterprise.server.AbstractLoader.load(AbstractLoader.java:244)
at com.sun.enterprise.server.AbstractManager.load(AbstractManager.java:225)
at com.sun.enterprise.server.ApplicationLifecycle.onStartup(ApplicationLifecycle.java:217)
at com.sun.enterprise.server.ApplicationServer.onStartup(ApplicationServer.java:442)
at com.sun.enterprise.server.ondemand.OnDemandServer.onStartup(OnDemandServer.java:120)
at com.sun.enterprise.server.PEMain.run(PEMain.java:411)
at com.sun.enterprise.server.PEMain.main(PEMain.java:338)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.enterprise.server.PELaunch.main(PELaunch.java:412)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.corba.ee.impl.codegen.CodeGeneratorUtil.makeClass(CodeGeneratorUtil.java:95)
… 23 more
Caused by: java.lang.VerifyError: class br.com.test._CounterImpl_Remote overrides final method getClass.()Ljava/lang/Class;
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
… 28 more
So, can you help-me? Thanks!
Hello Jair, I solved my problem. In CounterBean class, I put @Remote(CounterBean.class)..
I review my code more one time, and I saw this. =D… Thanks
Hi Zors,
Sorry for the late response, but I was in a business travel and I couldn’t check my personal email.
but I’m glad this tutorial had been good for you.
Hi Boss!
I have follow the all above steps on my Netbeans IDE 6.5. It’s too useful for us.
Thanks for guiding us.
Boss! I’ve a request to you that please tell us how to build Entity and Message Driven bean in Netbeans IDE 6.5.
Thanks again for the above topic.
Thanx & regards
(Manveer Singh)
Hi Manveer,
The entity is a simple POJO class. You won’t any special feature of the IDE. The JMS itself is a little harder. You must setup the application server to use it. For now, I just have a tutorial talking about JMS in Websphere 6.1. I’ll try to provide a new one for JBoss and Glassfish.
Thanks for leaving a comment
Your article is very helpful for me. Although I have a final exam tomorrow, it helps me to understand and test the simple EJB application in JBoss 4.0.2 by using Eclipse 3.4. Many thanks to the author of the article.
@EJB annotation work fine with JBoss 5.
Thanks for the article.
This tutorial does not what it says. The problem comes from the declaration of the counter attribute in the servlet :
private Counter counter;
This is wrong, as it will be common to all users. So if two different users call the CounterServlet, they will increment the same variable, and not two different counters.