Stateless Session Bean Dependency Injection in Servlet

6 March 2012 By Nithya Vasudevan 10,039 views 7 Comments
2 Flares Twitter 0 Facebook 1 Google+ 1 2 Flares ×

Environment Used

  • JDK 6 (Java SE 6)
  • EJB 3.x
  • Web Client – Servlet 2.5 API
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • JBoss Tools – Core 3.3.0 M5 for Eclipse Indigo (3.7.1)
  • JBoss Application Server (AS) 7.1.0 Final

Setting up development environment:
Read this page for installing and setting up the environment for developing and deploying EJB 3.x on JBoss application server.

Project Description

  • We are going to create a simple EJB 3 HelloWorld stateless session bean and a servlet client which will call/invoke the bean.
  • This “HelloWorld” example explains how to develop, deploy and run EJB3 Stateless Session Bean in JBoss application server.
  • We use Dependency Injection (DI) of stateless session bean in servlet.
  • The session bean and the servlet to access the session bean are deployed on the same server.

Creating New EJB Project

  • Open Eclipse IDE and create a new EJB project
  • Enter the project name as “HelloWorldSessionBean” and make sure the JBoss 7.1 Runtime has been selected with the EJB 3.0 Module version.
  • Click Next -> Next -> and Finish.
  • You will see an EJB project in the Project Explorer view.

Creating Session Bean and Bean Interface

  • Right click on ejbModule -> New -> Session Bean (EJB 3.x)
  • Enter the Java package name as com.theopentutorials.businesslogic
  • Enter the Class name as HelloWorldBean
  • Select the State type as Stateless
  • Check the Remote Business Interface and enter the name as com.theopentutorials.business.HelloWorld. The business interface will be created in different package (com.theopentutorials.business)
  • Click Finish

Coding Bean and the Interface

  • Open Bean Interface and type the following code and save the file (Ctrl+s).
package com.theopentutorials.business;
import javax.ejb.Remote;

@Remote
public interface HelloWorld {
	public String sayHello();
}
  • Open Bean and type the following code and save the file.
package com.theopentutorials.businesslogic;

import com.theopentutorials.business.HelloWorld;
import javax.ejb.Stateless;

@Stateless
public class HelloWorldBean implements HelloWorld {
    public HelloWorldBean() {
    }

	public String sayHello() {
		return "Hello World !!!";
	}
}

Creating Servlet Client (Dynamic Web Project)

  • The next step is to write a Web Client (a Servlet) which invokes the methods of bean.
  • The servlet uses Dependency Injection (DI) to get the bean reference.
  • Creating a new ‘Dynamic Web project’ can be done in three ways,
    • Right click on Project Explorer -> New -> Dynamic Web Project
    • File menu -> New -> Dynamic Web Project
    • Click on the down arrow on New icon on toolbar -> Dynamic Web Project
  • Enter the project name as “EJB3WebClient” and make sure the JBoss 7.1 Runtime has been selected with the Dynamic web module version as 2.5.
  • This project uses Java 1.6 version. The default Java version in Eclipse Indigo is 1.7 so to change the “Configuration” click on “Modify…” button and change the Java version from 1.7 to 1.6.
  • Click “Next” -> “Next” -> and “Finish”.
  • You will see the Dynamic web project in the “Project Explorer” view.

Since the Servlet is created in a separate project it needs EJB JAR file to do Dependency Injection.

Creating JAR file

  • Right click on HelloWorld.java interface file in HelloWorldSessionBean -> Export.
  • Expand Java folder and select “JAR file” and click Next.
  • Click on Browse… and enter the file name and Finish. In our example, the file name is given as HelloWorld

Now copy the created JAR file and paste it in EJB3WebClient/WebContent/WEB-INF/lib folder.

Creating Servlet class

  • Right click on src or Project -> New -> Servlet
  • Enter the Java package name as com.theopentutorials.servlets
  • Enter the Class name as EJB3ServletClient
  • Click “Finish

In the doGet() method copy the following code.

package com.theopentutorials.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.theopentutorials.businesslogic.HelloWorld;

public class EJB3ServletClient extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB(mappedName = "java:global/HelloWorldSessionBean/HelloWorldBean!com.theopentutorials.business.HelloWorld")
	HelloWorld bean;

	public EJB3ServletClient() {
        	super();
       	}

	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.println(bean.sayHello());  
	}
}

Deploying the dynamic web project

  • Now we need to deploy the Servlet project on server.
  • Right click on “JBoss 7.1 Runtime Server” available in Servers view -> Add and Remove… -> Select the Servlet WAR file from the left pane and click Add-> and then Finish.

Start/Restart the Server

  • Right click on “JBoss 7.1 Runtime Server” from Servers view and click on Start if it has not yet been started.

You will get the following output in the browser

Hello World !!!

For mappedName of @EJB annotation the following mapped names can also be used if the application server uses EJB3.1 look up naming convention, example JBoss AS 7
@EJB(mappedName = “ejb:/HelloWorldSessionBean//HelloWorldBean!com.theopentutorials.business.HelloWorld”)
HelloWorld bean;
@EJB(mappedName = “java:global/HelloWorldSessionBean/HelloWorldBean”)
HelloWorld bean;
NOTE: if the application server uses EJB3 look up naming convention, example JBoss AS 5 or 6 then the following mappedName should be used.
@EJB(mappedName = “HelloWorldBean/remote”)
HelloWorld bean;

NOTE:
To develop and run this example in JBoss AS 7, refer this page.
To develop and run this example in JBoss AS 6, refer this page.
To develop and run this example in JBoss AS 5, refer this page.

Tags: , , , , ,

  • praveena

    I am trying to inject ejb in the war file I followed as u explained but I am getting null.

    @EJB(mappedName=”java:global/Stakeholder/Stakeholder-ejb-1.0-SNAPSHOT/StakeholderIdentificationSb!com.werner.stakeholder.bp.StakeholderIdentificationSbLocal”)
    private StakeholderIdentificationSbLocal stakeholderIdeSbLocal;

    • http://theopentutorials.com nithya

      Need more details to give a solution. Have you used distinct name (Stakeholder-ejb-1.0-SNAPSHOT) in the lookup?

  • Dennis

    Hello!
    Thnak you for your example!

    I can call same HelloWorld-EJB without error from main class.
    But this error message comes through servlet from your example:

    09:46:05,976 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads – 2)
    {“JBAS014653: Composite operation failed and was rolled back. Steps that failed:” => {“Operation step-2″ =>
    {“JBAS014771: Services with missing/unavailable dependencies” =>
    ["jboss.naming.context.java.module.JBoss_EJB_JSF.JBoss_EJB_JSF.env.\"com.theopentutorials.servlets.EJB3ServletClient\".beanjboss.naming.context.java.global.HelloWorldSessionBean.\"HelloWorldBean!com.theopentutorials.business.HelloWorld\"Missing[jboss.naming.context.java.module.JBoss_EJB_JSF.JBoss_EJB_JSF.env.\"com.theopentutorials.servlets.EJB3ServletClient\".beanjboss.naming.context.java.global.HelloWorldSessionBean.\"HelloWorldBean!com.theopentutorials.business.HelloWorld\"]“]}}}

    please help…
    regards
    Dennis

  • Dennis

    it works without mappedName.

    @EJB
    HelloWorld bean;

  • Anil

    Thank you for your example.

    Could you please elaborate remote and local EJB’s?

    I am new to EJB.
    if i am not wrong,
    Local EJB runs on same JVM where the client is running.
    Remote EJB runs on different JVM where the client is running.

    how can we inject remote EJB by @EJB annotation?

    Please clarify.

    Thanks,
    Anil

    • http://theopentutorials.com Praveen Macherla

      As per the spec, local EJBs should only be invoked by clients running in the same application. So a client app (which is different from ear/jar) in same JVM as EJB container may not be able to invoke local ejbs. But many servers allow this.

      And for remote dependency injection, there is no standard way to do it. Each servers may have their ways. In our example we used the mappedName in servlet to specify the ejb.

  • rafael

    Hello, I get an exception when i try this tutorial. On my Browser i get a HTTP Status 404 EJB§WebClient is not available