Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create an enterprise web application using EJB Stateless Session Bean in EJB 3.X version

In this article, we will learn what stateless session bean is and how we do define a stateless session bean.

A session bean represent business logics of an application as distributes component, depending upon maintenance of intermediate state between multiple invocation of a bean. The stateless session bean does not maintain communicational state with a client. When a client invokes a method of stateless bean, a specific state is created for this method invocation. But, As soon as this method execution is finished, the state goes over and cannot be retained.

Objective:

Stateless Session in Detail:

A stateless session bean is represented by two components:

  • Remote Interface
  • Bean Class

Remote Interface is used to describe the business methods that are to be implemented by session bean. A remote interface needs to satisfy the following conditions:

  • It must extends javax.ejb.EJBObject interface and all the business methods that are declared in the Remote Interface. Hence, it must throw java.rmi.RemoteException.
  • javax.ejb.EJBObject interfaceextends remote interface and provides additional methods which facilitates the management of stub.
Remote Interface configuration Hierarchy

Figure 1: Remote Interface configuration Hierarchy

The above figure shows component interface or remote interface configuration hierarchy that extends EJBObject and the EBJObject extends Remote Interface. Hence, the all methods declared into the remote interface need to throw RemoteException.

This example is created using a Eclipse IDE and deployed on Weblogic 12C application server. To create an EJB project press key ctrl+n and type ejb to search ejb project type and press next after selecting EJB Project.

Place a project name “EJBDemo” and deployment source type as “Weblogic 12C” if already configured into IDE as shown in the figure 1:

Create a new EJB Project

Figure 2: Create a new EJB Project

The above figure show the new wizard to select EJB project type.

EJB Project Create wizard

Figure 3: EJB Project Create wizard

The above figure shows, how to create a new ejb project. Press Next and Next and click on “Generate ejb-jar.xml deployment descriptor” option and click Finish.

Once we finish wizard, it creates a required directory structure for EJB web application and creates a stateless session bean class file named FirstDemo.java and a remote interface named FirstDemoRemote.java file.

Listing 1: Remote interface

package com.demo;

import javax.ejb.Remote;

@Remote
public interface FirstDemoRemote {
	public String testDemo();
}

The above table code creates an Adder Interface that is a Remote Interface and extends EJBObject interface. A business method add() is declared into this interface that throws RemoteException. @Remote annotation defines the interface type as a Remote interface type.

The BeanClass implements the remote interface. An annotation class @Stateless is defined before the class declaration to define the session bean type that also defines the JNDI name using mappedName attribute as “FirstDemoEJB/Remote”.

Listing 2: FirstDemo.java

package com.demo;

import javax.ejb.Stateless;

/**
 * Session Bean implementation class FirstDemo
 */
@Stateless (mappedName = "FirstDemoEJB/Remote")
public class FirstDemo implements FirstDemoRemote {

    /**
     * Default constructor. 
     */
    public FirstDemo() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public String testDemo() {
		// TODO Auto-generated method stub
		return "Test Demo";
	}

}

Above file defines a stateless session bean, implementing the FirstDemoRemote interface methods.

To compile ejb application, it is required to have the javax.ejb package associated with the project classpath. You may find this packaged jar file into the installed WebLogic application server directory path “Oracle\Middleware\modules\javax.ejb_3.1.0.jar”. To import this jar file, right click on the project and build path=>configure build path and click on Add External Jar File and add the required jar file from the location:

To compile and deploy an ejb application on the application web server, we are required to import javax.ejb package into the classpath of Remote EJB application. It can be found in the WebLogic application server installed directory:

<installation-directory>:\Oracle\Middleware\modules\javax.ejb_3.1.0.jar

Few other jar files are required for client application that invokes methods from Remote EJB application. The required jar files are:

  • servlet.jar
  • jsp.jar
  • weblogic.jar

Directory structure for these jar files are as follows:

  • <installation-direcotry>:\Oracle\Middleware\modules\javax.jsp_2.0.0.0_2-2.jar
  • <installation-direcotry>:\Oracle\Middleware\modules\javax.servlet_2.0.0.0_3-0.jar
  • <installation-direcotry>:\Oracle\Middleware\wlserver_12.1\server\lib\weblogic.jar

Once we have configured and created an EJB application, we are required to create an ear type bundle of this EJB application that can be deployed on the application web server. To crate an ear type bundle of this application, right click on the ejb project in eclipse and choose export that open an export wizard.

Eclipse Export Wizard

Figure 4: Eclipse Export Wizard

Choose an ear export type and give the destination for export with the file name and click Finish.

Now to deploy this application on the application server, start weblogic server and open console using url: http://localhost:7001/console

Login into the console using account information crated. Click on the Deployments from the right menu of the web page. Click on install and choose the ear file from the destination to be deployed and click next -> next -> finish. In the next screen, we will get our EJB application deployed on the application web server.

Deployed EJB application on the application server

Figure 5: Deployed EJB application on the application server

In the above figure, pointer 1 shows the deployment url, pointer 2 shows install tab and pointer 3 shows the deployed ejb application.

Now crate a client application that invoke the ejb application method testDemo(). It will be lookedup and testDemo() method will be invoked. A remote interface will be placed as jar into the classpath of client project and servlet file named TestServlet.java will be crated to invoke remote interface method that is implemented in the remote application. To create a jar file of remote interface, right click on the remote application and choose export that opens an export wizard, type jar to choose a jar type export and click next and choose remote interface to be exported as jar file.

Export Remote Interface as Jar file

Figure 6: Export Remote Interface as Jar file

The above figure shows jar file export wizard to export Remote interface. Now import the Remote Interface Jar into our client application using build path setting. Right click on client project and choose Build Path->Configure Build Path->JavaBuildPath Wizard. Now click on Add External Jar to import Remote Interface jar file and click finish. Now crate a TestServlet.java class file.

Listing 3: TestServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.demo.FirstDemoRemote;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		Properties p = new Properties();
		p.setProperty("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
		p.setProperty("java.naming.provider.url", "t3://localhost:7001");
		p.setProperty("java.naming.security.principal", "weblogic");
		p.setProperty("java.naming.security.credentials", "welcome1");
		
		try{
			InitialContext ctx = new InitialContext(p);
			Object obj = ctx.lookup("FirstDemoEJB/Remote#com.demo.FirstDemoRemote");
			out.print(obj);
			/*
			 * Export it as a war file and deploye it on the same server.
			 */
			FirstDemoRemote remote = (FirstDemoRemote) obj;
			String result = remote.testDemo();
			out.print(result);
		}
		catch(Exception e){
			out.print(e.getStackTrace());
			out.print("Error");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

The above file creates a servlet named TestServlet and @WebServlet annotation is used to define a urlpattern for this servlet as “/TestServlet”. This class is extended by HttpServlet and defined a doGet() method that invokes the remote method testDemo() using following steps:

  • Define a response type using response.setContentType();
  • Define a writer object using PrintWriter class of java.io package.
  • Define a property for application server using Properties class defined in java.util package.
  • The properties object calls setProperty() method that accepts two arguments key and values. This method is used to used initialize properties used by InitialContext that initialize WebLogic naming factory initial value as:
  • "java.naming.factory.initial" & "weblogic.jndi.WLInitialContextFactory"
  • "java.naming.provider.url" & "t3://localhost:7001"
  • "java.naming.security.principal" & "weblogic"
  • "java.naming.security.credentials" & "welcome1"
  • Create an InitialContext object and call a lookup() method for JNDI name and its remote interface as :
InitialContext ctx = new InitialContext();
Object obj = ctx.lookup("FirstDemoEJB/Remote#com.demo.FirstDemoRemote");
  • Now print object received from JNDI to check proxy object values.
  • Typecast the received object to Remote Interface object and invoke remote method on it as :
FirstDemoRemote remote = (FirstDemoRemote) obj;
String result = remote.testDemo();
out.print(result);
Directory Structure

Figure 7: Directory Structure

The above figure shows directory eclipse ide structure crated for both client and remote web applications.

Now right click on the client project and export the war file as bundle of client web application. Now deploy this war file on the application web server in the same way as ear file was deployed. Now visit the TestServlet on that respond as shown into the following figure:

Invok testDemo() method while TestServlet is loaded

Figure 8: Invok testDemo() method while TestServlet is loaded

The above figure shows the proxy object returned from the JNDI and response string from invoked remote method testDemo(), which is “Test Demo”.

Conclusion:

In this article, we learn:

  • What is stateless session bean?
  • How do we define a stateless session bean?


Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login