Example of EJB3 (Session Bean) using Eclipse Europa and JBoss
Posted by jrjuniorsp on April 25, 2008
After the frustration of EJB 2, EJB 3 is growing in the community every day.
Different from EJB 2, EJB3 is simpler and much productive. However you have to pay attention before work with EJB3.
First of all, you have to make sure that your Production environment has Java 5 version, as well as your Application Server is JEE 5-compliance. Many servers do not have this configuration yet. (I myself work in a project that uses J2EE 1.4).
Also, EJB 3 does not need to be used in ALL applications. You have to think if in your project EJB is really necessary. In general, EJB are used when you need of distributed components.
JBoss is one of the most popular open-source Application Server and its version 4.2 supports JEE 5. Glassfish from Sun is also another good choice for free application server.
In this topic I am going to show you a simple example of how to create a Session Bean using Eclipse Europa and JBoss Application Server. If you do not have the JBoss AS installed, you can check this topic to install it.
After install Java 5 or 6, JBoss AS and Eclipse Europa, it is time to create the application itself. Let’s open the Eclipse and prepare our developer skill
Configuration JBoss within Eclipse Europa
Inside the Eclipse Europa, open the Servers view (Window -> Show View -> Servers). Right mouse click on Servers view and choose option New -> Server.
Choose the JBoss 4.2 and its path. After that the JBoss server should appear on the Servers view.
Creating the Enterprise Application Project
On Eclipse IDE (Using the Java EE perspective), right mouse click on Package Explorer and go to New -> Enterprise Application Project.
Choose the Project Name (e.g: TestApplication), Target Runtime (JBoss 4.2) and click on Next button.
On the next screen keep the EAR checked and click on Next. On the third screen, click on New Module button to select the modules you want to install. Let’s work on with two modules (EJB and Web). Choose these modules and click OK. Also, on third screen mark the option Generate Deployment Descriptor.
After that, the Enterprise Application Project will be created, as well as the EJB and Web modules. All of them can be reached in the Package Explorer.
Creating our first EJB component (Stateless Session Bean)
In Eclipse Europa, there is not an option to create a EJB component itself. You have to do it manually. However in the new EJB version, you can use Annotations rather than a Deployment Descriptor (XML) to map your components. As the annotation is much easier than XML, you will not loose productive in the component development.
Remember: In EJB 3 you need only two files: an Interface (local or remote) and its implementation. By default, the interface receives the name of the component and the implementation receives the name of the component plus Bean.
The first think to do is to create our Interface. In your example, we are going to use a simple Session Bean which has one method (public void getMessage). So creates this interface inside the EJB project. Right mouse click on TestApplicationEJB -> New -> Interface.
Also, put the method public String getMessage(); into this interface.
package lesson.stateless;
public interface HelloWorld {
public String getMessage();
}
The next step is to create the class that implements this interface. The pattern is the class has the same name than the interface plus Bean.
To create a click, right mouse click on TestApplicationEJB -> New -> Class. Insert the class name and choose the Interface.
Note: As the interface calls HelloWorld, than our class calls: HelloWorldBean.
Now it is time to implement the HelloWorldBean.java class. It is a simple class which contains only one method. Look at its implementation below:
package lesson.stateless;
import javax.ejb.Remote;
import javax.ejb.Stateless;
@Stateless
@Remote(HelloWorld.class)
public class HelloWorldBean implements HelloWorld {
public String getMessage() {
return "Hello EJB World";
}
}
Pay attention on line 6 and 7. The @Stateless annotation tells to the AS which the component is a Stateless Session Bean. Also, the @Remote annotation tells to the AS which interface is the remote for this implementation.
Done! Our EJB module is done to be deployed. If you are coming from EJB 2, you can see how the EJB 3 is much easier and productive
Using the Web Module as EJB Client.
It is common you have in the same EAR a EJB Module and a Web Module. In this case, the Web module works as a EJB Client, in other words, the We Module is going to be the FRONT-END as long as the EJB Module is going to be the BACK-END.
In our example we will use a simple Web Module. A single JSP file that call a servlet. The servlet makes connection with the EJB Module and print out in the console the message from EJB.
First of all, let’s create the JSP file. Expand the TestApplicationWeb and right click on WebContent -> New -> JSP. Create a jsp with the name index. Inside the JSP, put a call to the servlet. Let’s call our servlet as TestServlet. The JSP content could be anything like this:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<h1>Web Module used as EJB Client</h1>
<a href="TestServlet">Click here to call the EJB component</a>
</body>
</html>
Now it is time to create the Servlet component. Right mouse click on TestApplicationWeb -> New -> Servlet. Put the name TestServlet and choose a package (if you want).
Before implement this method, we need to create a binding between the Web Module and the EJB Module. To do that right mouse click on TestApplicationWeb -> Properties.
Go to J2EE Module Dependencies and mark the option TestApplicationEJB.jar. Thus your Web module will see the EJB interfaces, but remember, you cannot call it directly.
Now we are able to implement the servlet. We are going to use only the method doGet (fell free to get rid of the doPost method). Inside the doGet method, we are going to call the EJB component and show its return message.
package lesson.servlets;
import java.io.IOException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lesson.stateless.HelloWorld;
public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
InitialContext ctx = new InitialContext();
HelloWorld hello = (HelloWorld) ctx.lookup("TestApplication/HelloWorldBean/remote");
System.out.println(hello.getMessage());
} catch (NamingException e) {
e.printStackTrace();
}
}
}
Check out the lines 18 to 20.
- In the line 18, we start an InitialContext object. As we are working inside the same EAR than the EJB, we cannot pass none parameter for its constructor. In the next example (Creating a Java stand-alone client), you will see that a Properties file is required.
- In the line 19 we call the remote object HelloWorld. Pay attention on its JNDI name. The JBoss pattern is: First the EAR name / The EJB Implementation Component / remove or local. The ctx.lookup method looks for the remote object inside the EJB module and returns its instance.
- In the line 20 we prints out the return of the getMessage() method.
Note: The annotation @EJB does not work properly in JBoss server. If anyone had success using this annotation, please let me know :).
Now you can run this application. Right mouse click on TestApplicationWeb -> Run As -> Run on Server. The first time you try to run the application, a screen regarding server configuration will come up. Select the JBoss 4.2 server (you previosly configurated) and mark the option Always use this sever when running this project. Click OK and the server will starts.
Inside the Eclipse you will see the web page. Click on the link and look at the Eclipse Console. A message from EJB should appears for you.
Creating a Java Stand-Alone Client
You should use EJB when you need of distributed components. Besides use distributed components in the server (through clustering, SOA, and so on), you can create a communication between a Stand-Alone application.
A Stand-Alone application calls the EJB in a similar way then Web Modules, however it has some particularities.
- You have to import some JBoss libraries to the stand-alone application
- You have to create a Properties file and use it in the InitialContext object
- The Stand-Alone application must “know” the remote components interfaces.
Create a Java Project, File -> New -> Project -> Java Project.
Import the following two files to this project
jbossall-client.jar jboss-ejb3-client.jar
You can find these files inside $JBOSS_HOME/client directory. To add them to the Project classpath, right click on Java Project -> Propeties. Go to Java Build Path -> Libraries -> Add External JARs.
Also, inside the Properties screen, click on Projects tab and then Add button. Select the EJB module. This way your client application will see the remote ejb object.
Create a properties file (called jndi.properties) in the root of the Client project. The content of the file is below:
java.naming.factory.initial = org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs = org.jboss.naming:org.jnp.interfaces java.naming.provider.url = localhost:1099
Now create a simple Java class containing the void main (String args[]) method.
Implement this method, using the Properties file previously created as argument to InitialContext object.
package lesson.client;
import java.io.FileInputStream;
import java.util.Properties;
import javax.naming.InitialContext;
import lesson.stateless.HelloWorld;
public class TestClient {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.load(new FileInputStream("jndi.properties"));
InitialContext ctx = new InitialContext(props);
HelloWorld hello = (HelloWorld) ctx.lookup("TestApplication/HelloWorldBean/remote");
System.out.println(hello.getMessage());
}
}
Before run the client application, make sure the Application Server is running. If so, runs your Main class and see the output in the Eclipse Console view.
This topic ends here. I hope this topic can help the people who wants to work with EJB in Eclipse Europa. The next topic is the same example, but using Netbeans 6.1 and Glassfish. I hope you enjoy it.












April 28, 2008 at 12:56 pm
Hello,
i did exactly as you told (with jboss 4.2.2GA and then 5.0.0.Beta4).
but i get this error message:
I am thankful if you have an idea.
Parviz
Exception in thread “main” javax.naming.CommunicationException [Root exception is java.io.InvalidClassException: org.jboss.ejb3.remoting.BaseRemoteProxy; local class incompatible: stream classdesc serialVersionUID = -2711693270411201590, local class serialVersionUID = 1126421850898582900]
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:723)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:58
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at client.SimpleSessionClient.main(SimpleSessionClient.java:24)
Caused by: java.io.InvalidClassException: org.jboss.ejb3.remoting.BaseRemoteProxy; local class incompatible: stream classdesc serialVersionUID = -2711693270411201590, local class serialVersionUID = 1126421850898582900
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:562)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1583)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1583)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1583)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1945)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1869)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at java.rmi.MarshalledObject.get(MarshalledObject.java:142)
at org.jnp.interfaces.MarshalledValuePair.get(MarshalledValuePair.java:72)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:653)
… 3 more
April 28, 2008 at 2:15 pm
It seems a lookup problem (Communication between the Client and the EJB remote object).
Are you using a stand-alone client or a WebModule inside the same EAR file?
I did not get this error before, so try a search in google and hopefully you will find your answer.
April 28, 2008 at 3:27 pm
Hello again
I found it, i did a mistake and i compile the code with other library (not current liraries of jboss) and therefore i got this error message. your tutorial is excellent!
Parviz
April 29, 2008 at 7:10 pm
Hi,
Thanks for the excellent tutorial for the basic project creation. It helped me in creating my first EJB 3.0 project.
Thanks again.
Ravi
April 30, 2008 at 7:00 am
I have to honesty say that this is the best simple example (for the beginners) which I have found.
Keep on doing the good work – simple, very clear, very nicely put together example.
ToMaZ from Slovenia
May 8, 2008 at 8:27 am
I this is simply the best example for EJB 3.0
Good Work.. it really helped a lot… thanks again…
May 13, 2008 at 7:25 am
Hai, Am getting following Error.
This is while building:
***********************
—————————————————————————————————-
BUILD FAILED
E:\eclipse\plugins\org.eclipse.jst.server.generic.jboss_1.5.105.v200709061325\buildfiles\jboss323.xml:33: Unable to remove existing file D:\jboss-5.0.0.Beta4\server\default\deploy\TestApplication.ear
Total time: 250 milliseconds
—————————————————————————————————-
This is while running:
**********************
12:53:08,135 ERROR [STDERR] javax.naming.NameNotFoundException: TestApplication not bound
12:53:08,135 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:542)
12:53:08,135 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:550)
—————————————————————————————————-
Could you please assist me. Thanks, Kind regards.
May 13, 2008 at 11:49 am
It seems the deploy was not done successfully.
Try to undeploy the application (TestApplication.ear) yourself and run it again from Eclipse.
To undeploy an application on JBoss, the easiest way is delete the .ear file, in you case, delete the TestApplication.ear into D:\jboss-5.0.0.Beta4\server\default\deploy\ directory.
After that, run JBoss again (outside from Eclipse) and see if any exception is thrown on console, if not, try to deploy and run the AS from Eclipse.
Good luck
May 15, 2008 at 11:44 am
Hai Jrjuniorsp Thanks. Now Build issue is resolved. Deloy it is a problem.
—————————————————————————
7:09:54,750 ERROR [STDERR] javax.naming.NameNotFoundException: TestApplication not bound
17:09:54,750 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:542)
17:09:54,750 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:550)
17:09:54,750 ERROR [STDERR] at org.jnp.server.NamingServer.getObject(NamingServer.java:556)
17:09:54,750 ERROR [STDERR] at org.jnp.server.NamingServer.lookup(NamingServer.java:267)
——————————————————————————————-
I deploy it by doing Export>>EJB>>EJB Jar file and Export>>Web>>WAR file and placed it under
JBoss deploy folder. Please correct me if am wrong. Thanks cheers.
May 15, 2008 at 12:27 pm
Gamesam,
Try to export only the .EAR file.
Right click on “TestApplication” and go to export.. Export it as EAR file. When you do that, both EJB and WEB modules are going to be exported as well.
Build only the .EAR file.
TIP: If you are using Eclipse Europa, you can run your application directly from the Eclipse. Right click on Web project and go to Run as -> Run on Server.
May 15, 2008 at 9:52 pm
Thank’s a lot. The tutorial is very good
May 16, 2008 at 4:42 pm
This tutorial is really good. But I’m facing a problem while running the stand-alone application. I’m getting the below error. I have properly set the classpath also (with the couple of jars mentioned). Appreciate ur help in this.
Exception in thread “main” javax.naming.NoInitialContextException: Cannot instantiate class: org.jnp.interfaces.NamingContextFactory [Root exception is java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory ]
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.(Unknown Source)
at lesson.client.TestClient.main(TestClient.java:15)
Caused by: java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sun.naming.internal.VersionHelper12.loadClass(Unknown Source)
… 5 more
May 16, 2008 at 5:51 pm
Hi Jams,
It’s weird because I hadn’t this problem before. It seems your application requires the JPN lib.
Looking for this problem in google I found this topic: http://forum.java.sun.com/thread.jspa?threadID=561402&messageID=2762420
I think it can help you.
May 17, 2008 at 3:49 am
Hi,
Thanks for you reply and solution approach.
I tried including jnp-client.jar in the classpath, but still I’m getting the error.
org.jnp.interfaces.NamingContextFactory seems to be there in jbossall-client.jar itself, but I’m wondering why this happens.
Any Idea???
May 17, 2008 at 4:53 pm
Hi Jams.
Which JBoss AS version are you using? Not sure why it is happening, but try to get the latest JBoss AS version. (I’m using version 4.2.2 GA).
May 18, 2008 at 4:11 pm
Hi,
I’m using jboss-4.2.0.GA and Eclipse Europa 3.3.1 (WTP).
Thanks for your help, I will try with 4.2.2.
May 26, 2008 at 9:18 am
hi friends, please let me know if somebody have an idea to create a client jar file in ejb3. like in ejb2 we can specify in the ejb-jar.xml file and the weblogic server creates the corrosponding client jar file. but im not getting the idea how we can create the client jar file in ejb3 without using the deployment descritptors.
thanks
May 28, 2008 at 4:31 pm
Hi, Thanks for a nice tutorial!
June 1, 2008 at 9:39 pm
Hey,
I have the same problem as Jams, and my classpath includes all the Jboss libraries.
That is the TestApplicationEJB and the TestApplicationWeb.
Does anyone has any more ideas?
June 3, 2008 at 9:03 am
Hello,
thanks for this very useful tutorial.
unfortunately i have a problem, when deploying the project to jboss:
org.jboss.deployment.DeploymentException: No META-INF/application.xml found
did i forget to create automatically a file on one point? i’m also using jboss 4.2.2 and eclipse wtp
thx in advance for help
June 3, 2008 at 11:29 am
Make sure your application.xml file lives in WEB-INF/classes/META-INF/application.xml.
A tip: In eclipse IDE, create a META-INF directory inside the “src” directory. Thus, eclipse automatically will deploy this directory, as well as the application.xml file, to WEB-INF/classes
June 3, 2008 at 9:19 pm
In response to Rolf and Jams getting the NamingContextFactory class not found exception, I had the same problem until I found that my jndi.properties file (copy/paste from the tutorial!) had a few blank spaces at the end of each line. When I removed the whitespace, the sample code worked!
June 4, 2008 at 12:57 pm
i have no application.xml and no idea how to create it… however i found no point in the tutorial where such a file is created.
June 4, 2008 at 1:02 pm
You’re right.. You’re following the tutorial, you do not need the application.xml file. It is used when you are going to use JPA as well.
I have no idea why JBoss is complaining about this file. But anyway, try to create it (look for an example in google) and try to re-deploy your application.
June 9, 2008 at 10:05 am
Its an excellent document for larner
Thanks a lot to creator
June 13, 2008 at 1:00 pm
hi,
i had been trying to run my ejb program in myeclipse for one weak. but i couldn’t get success. i was getting jndi problems. but when i followed ur guide lines, i got success. thanks very much for this beautiful information
June 16, 2008 at 1:30 pm
Hi,
I have created my first EJB with this simple and precise example. Really good one to start EJB for beginners.
June 16, 2008 at 1:38 pm
Hi,
When i try to execute the EJB standalone client appllication, it couldn’t find Class “NamingContextFactory” class specified in Properties file. Then I defined “java.naming.factory.url.pkgs” first and “java.naming.factory.initial” next. It started working.
I couldn’t figure out why it couldn’t work intially.
June 19, 2008 at 7:40 pm
Jr,
Uma Excelente Matéria, diria até, Espetacular !!!
Um Tutorial simples e eficiente e enxuto - só tem o que precisa.
Parabéns !!!
June 20, 2008 at 8:32 am
Great tutorial for beginners. Thanks for this.
I have one suggestion.
When you create your EJB project, select option to create an EJB client project. Then create all your client interfaces in this client project. The ejb module and the web module then should be dependent on this client module.
This way if you ever have to separate EJB module and the web module into different deployment units, you will not have to include your bean classes in the web module.
June 27, 2008 at 11:37 pm
Hi,
i’m facing a problem during the lookup, i get the following error “TestApplication not bound”
This is the stack trace
2008-06-27 20:27:28,734 DEBUG [org.jboss.deployment.MainDeployer] Deployed package: file:/E:/jboss-4.2.2.GA/server/default/deploy/TestApplication.ear
2008-06-27 20:27:28,734 DEBUG [org.jboss.deployment.scanner.URLDeploymentScanner] Watch URL for: file:/E:/jboss-4.2.2.GA/server/default/deploy/TestApplication.ear -> file:/E:/jboss-4.2.2.GA/server/default/deploy/TestApplication.ear
2008-06-27 20:27:39,625 ERROR [STDERR] javax.naming.NameNotFoundException: TestApplication not bound
2008-06-27 20:27:39,625 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:529)
2008-06-27 20:27:39,625 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:537)
2008-06-27 20:27:39,625 ERROR [STDERR] at org.jnp.server.NamingServer.getObject(NamingServer.java:543)
2008-06-27 20:27:39,625 ERROR [STDERR] at org.jnp.server.NamingServer.lookup(NamingServer.java:267)
2008-06-27 20:27:39,625 ERROR [STDERR] at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:667)
2008-06-27 20:27:39,625 ERROR [STDERR] at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:627)
2008-06-27 20:27:39,625 ERROR [STDERR] at javax.naming.InitialContext.lookup(Unknown Source)
Any idea? i am a newbie on this, thanks for the tutorial
June 28, 2008 at 12:31 am
Solved, it was a copy and paste error
excellent tutorial
July 3, 2008 at 8:34 am
Hi,
did my first EJB example.very helpfull.good to start with
thanks
Hima
July 3, 2008 at 3:51 pm
Hi,
Thanks for this excellent titorial!!! Finally I was able to run an EJB project.
Now I’m looking for an example on writting Session Bean Web Services. I think it´s not as easy as writtng @WebService on my HelloBean. Do you have a tutorial on this? Any idea on where to find this out?
Thanks a lot!!
Catalina
July 3, 2008 at 5:00 pm
Hi Catalina,
Thanks for you feedback. I’m glad to hear it.
Well, I have no tutorial about Webservices yet :(, however it is easy too. The biggest problem (in my opinion) is to create the Client to access the Webservices.
This is a good idea for a new tutorial.
Jair Rillo Junior