JBoss.org Community Documentation

Chapter 11. Introduction to EJB injection in Servlets

This tutorial aims at showing how EJBs can be injected in a Servlet. In this tutorial we build an EAR file which contains a EJB module (jar file) and a web module (war file).

Take a look at the META-INF/application.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC
	"-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
  <description>Enterprise application showing injection of EJB in Servlet</description>


EJB module:

The EJB module in this tutorial consists of a EJB3 SLSB. Take a look at org.jboss.tutorial.enterprise_app_ejb_injection.bean.CalculatorBean:

public class CalculatorBean implements CalculatorRemote, CalculatorLocal

We will be using this bean in the servlet for performing the add and subtract operations.


When a EJB packaged in a jar file is deployed as part of an EAR, the default jndi-name for the business-remote interface will be of the form EARName/BeanName/remote. Similarly the local business-remote will have the default jndi-name of the form EARName/BeanName/local.

Web module:

The web module consists of a index.html and a servlet org.jboss.tutorial.enterprise_app_ejb_injection.servlet.CalculatorActionServlet. Take a look at the WEB-INF/web.xml which configures the index.html as the welcome page and also maps the servlet.


<!-- The servlet and jsp page mappings -->



The org.jboss.tutorial.enterpise_app_ejb_injection.bean.CalculatorLocal will be injected in the org.jboss.tutorial.enterprise_app_ejb_injection.servlet.CalculatorActionServlet using the @EJB annotation:

private CalculatorLocal calculator;

 * Injecting the EJB
@EJB(name = "calculator")
public void setCalculator(CalculatorLocal calculator)
   this.calculator = calculator;


For the injection to take place in a web module, your web.xml should use the 2.5 version of the web-app xsd:

<web-app version="2.5"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

Building and Running

From the command prompt, move to the "enterprise_app_ejb_injection" folder under the Section 1.3, “Set the EJB3_TUTORIAL_HOME”

Ant Users:

Make sure your JBossAS-5.x is running

$ ant

This will deploy the ear into the JBossAS-5.x server ("default" configuration).

To access the servlet, open a web browser and enter http://localhost:8080/jboss-ejb3-tutorial-enterprise_webapp. This will bring up a page where you can enter two number and either click on Add or subtract.
Maven Users: Make sure the AS is not running.
$ mvn clean install -PRunSingleTutorial

This will create the EAR in the target folder of the tutorial. Copy this EAR to the deploy folder of JBossAS-5.x and start the server (if it's already not started). Then follow the steps mentioned above, to access the servlet from the web browser.