Sunday, February 1, 2009

How to call a EJB from a jsp or servlets..

Hi All,
In this post we will learn that how to call a session bean in EJB3.0 from a simple jsp so one can kick start their new project or any new application.

In this post, i am going to use the eclipse 3.4 as IDE and Jboss 5.0 as application server.
It is because, in various tutorials which are available on the internet very less are using eclipse as IDE and if they are using eclipse , it is very old version eclipse which is not being used now days.

I am giving the whole procedure into number of steps.
I have tried my best to brief each and ever thing to deeper extent so that a fresher can understand.

Step 1-> Open your eclipse. Go to the File menu. Click one the new project.
It will ask you which type of project you want to create. Here choose the EJB project.
It will open a pop up window in front of you containing the various options which we need to be filled by ourselves. I am going to explain them one by one. The first option is the name of the project i am giving here "VariousJavaTech-Ejb3Demo". The second option is about the Target Runtime. It will ask for the server details which you want to use in current project. I am using Jboss 5.0. Third option is the EJB Module Version. Select the version 3.0 from the drop down list. In Fourth option select the Default Configuration For the JBoss5.0.
Fifth option is for EAR membership. Click on the check box because we want to add our project in the EAR file. Now click on the next button.
On the next page you will see again some options. First one is the source folder for the ejb's which we are going to use. You can give any name here. Below it you will see a check bos mentioning create an ejb client jar to hold the client interfaces and classes. Then click on the finish button. This will create three separate projects in eclipse named as :

1)VariousJavaTech-Ejb3Demo-> This will hold your beans code.
2)VariousJavaTech-Ejb3DemoClient->This will hold your client interfaces both for remote and local.
3)VariousJavaTech-Ejb3DemoEAR->This will be the EAR file for your project.

This will complete your first step.

Step 2) -> In this step we will see how to create the session bean and its assocaite intefaces in ejb3. Go to the VariousJavaTech-Ejb3Demo project. Open it and right click on the source folder i.e ejbModule and click on the create new session bean. A new pop up window will open which will contain some information and need some information to complete the current task.
You will see the first option of EjbProject. In our case it is VariousJavatech-Ejb3Demo. Do not change it. The second option will be about the source folder you can give anything you want. In my case i am not going to change it. Then fill the package name i am giving "com.variousjavatechs.ejb" and class name as "DemoSessionBean".
Now the important part, select the session bean type. As i m developing a simple session bean , i am using the stateless session bean. Last option will be regarding the interfaces. Wehter you want to create loca or remote interfaces related to your ejb. I am selecting the Local interfaces as my whole application will reside on the same machine. Your eclipse will automatically take this name as "com.variousjavatechs.ejb.DemoSessionBeanLocal" .
Now click on the next button. Do not change the anything on the next screen. Every option on this screen is self explaintory, you can change the things if you want to change them. Now click on the finish button. After this you will see that "DemoSessionBean" will be created in the "VariousJavaTech-Ejb3Demo" project and "DemoSessionBeanLocal" interface in the
"VariousJavaTech-Ejb3DemoClient". This ends our second step.

Step 3) -> In this step we will do some coding. Look at the "DemoSessionBeanLocal" interface. You will see annotation like @Local in this interface which make sure that it is a local interface. Also we do not need to create any home interface in ejb3. It is the true power of ejb3.
Now, define the following method in "DemoSessionBeanLocal".

public String getString();

As DemoSessionBean class implements DemoSessionBeanLocal, we need to declare this method in the DemoSessionBean. You can also see the annotaion @Stateless sign on the DemoSessionBean class. Which shows it is a stateless session bean.
I am defining the method body like :

public String getString() {
return "Hello Various Java Techs";
}

It completes our ejb part. Step 3 ends here.

Step 4) -> In this step we will create the web part of our ejb demo application. Create a new dynamic web project in eclipse. Name it as "VariousJavaTech-Web". Assign the target runtime Jboss5 and Click on the ckech box i.e. add project to an EAR file. In our case the EAR file will be "VariousJavaTech-Ejb3DemoEAR". This will add our web project into the existing EAR file so this step will register the ejb part with web part through the EAR file. Our EAR file will be holding the WAR file from web project and jar file from EJB project.
Now click on the next button. No need to changing anything on the second screen. Now we will create a simple jsp will try to access our session bean in this jsp.

I am giving the full code for the jsp. Note down the JNDI name used to access the EJB beans.
You can see these JNDI names from the jboss web console or you can also see them in the console of eclipse while deploying this application on the server.
The code is given below:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="com.variousjavatechs.ejb.*,javax.naming.*,java.util.Properties"%>

<%!private DemoSessionBeanLocal demo = null;
String str; public void jspInit() {
try {
InitialContext ic = new InitialContext();
demo = (DemoSessionBeanLocal) ic .lookup("VariousJavaTech-Ejb3DemoEAR/DemoSessionBean/local");
System.out.println("Loaded Demo Bean");
} catch (Exception ex) {
System.out.println("Error:" + ex.getMessage());
}
}
public void jspDestroy() {
demo = null;
}
%>


<% try { str = demo.getString(); %>

The result is: <%=str%>

<% }// end of try
catch (Exception e) {
e.printStackTrace();
result = "Not valid";
} %>

Most important process in this step is , right click on the VariousJavaTech-Web . Now go to the properties and click on the Java EE Module Dependencies. Here you need to give the reference to the EJB Client Jars which you want to use in your current web project. So in my case i am giving reference to "VariousJavaTech-Ejb3DemoClient.jar"

This ends our strep 4.

Step 5) -> In this step we will run our application. Only you need to right click on your jsp page and click on run on the server and select jboss as server.
It will start deploying your EJB application. Look at the console after the complete deploying it should look like :

6:15:50,457 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

VariousJavaTech-Ejb3DemoEAR/DemoSessionBean/local - EJB3.x Default Local Business Interface
VariousJavaTech-Ejb3DemoEAR/DemoSessionBean/local-com.variousjavatechs.ejb.DemoSessionBeanLocal - EJB3.x Local Business Interface

16:15:50,567 INFO [TomcatDeployment] deploy, ctxPath=/VariousJavaTech-Web, vfsUrl=VariousJavaTech-Ejb3DemoEAR.ear/VariousJavaTech-Web.war
16:17:44,013 INFO [STDOUT] Loaded Demo Bean


Its mean your application is deployed successfully.
Now go to the browser and write the following in the url

http://localhost:8080/VariousJavaTech-Web/callSessionBean.jsp

You will see the following output.

The result is: Hello Various Java Techs.
This ends your step 5.

Mail me or post any comment if getting any problem.

Thanks.