Using Dependency Injection in Struts2 for stateless EJBs part 1

In this post I will present a way to use dependency injection of stateless session beans in Struts 2 actions using Guice. I will only write about EJB3, because they have simpler client lookup code, but you might be able to change the presented code to cover older versions of EJB.

We will use off the shelf Struts 2 and off the shelf Guice (with the Guice Struts 2 plug-in). No extra “glue” code is required to inject stateless EJBs into a Struts actions with Guice. In the next post I will tweak the presented code and make the binding of EJBs in Guice modules simpler.

This post is divided in two sections. In the first section we will create a simple, complete, hello-world type application using Struts 2. The application will consist of only one action that when called will print the current date in a JSP page. Then we will write a stateless session EJB and use Guice to inject the EJB into the action. If you are already familiar with Struts 2 you might want to skip the first section and go directly to the second.

A basic Struts 2.x application

Below you will find a series of steps with all code for our mini application.

1. Project setup

With your favorite IDE create an enterprise project. You need to create an enterprise project (ear based deployment) and not a web project (war based deployment) because we will create an EJB in the next section.

Now add a web module into your enterprise project and add the following jars to WEB-INF/lib: commons-logging-1.1.jar, freemarker-2.3.8.jar, ognl-2.6.11.jar, struts2-core-2.0.8.jar and xwork-2.0.3.jar.

Although I am a happy Eclipse user I have to admit that Eclipse has very basic support for Java EE 5, so for the code of this post I used Netbeans 6.0 M9 with Glassfish 2 Beta as the application server. Netbeans IMHO is not so good for Java editing but has decent support for the latest Java EE standards. Please keep in mind that the code is only tested with Glassfish 2 Beta.

2. Edit web.xml

The below code is the minimum web.xml needed for a Struts 2 application. It contains the Struts 2 filter definition (FilterDispatcher) and a welcome file (index.html) that it is used to redirect the user to the default Struts 2 action.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

3. Create struts.xml

Now we need to create the struts.xml file. This file is located at the root of your classpath. The below code has some basic configuration parameters and includes the dates Struts package that will contain our action.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <constant name="struts.enable.DynamicMethodInvocation" value="false" />
  <constant name="struts.devMode" value="false" />
  <!-- Include the package with our actions -->
  <include file="dates.xml"/>
</struts>

4. Create the dates Struts package

Create the dates.xml file at the root of your classpath as we specified in the above struts.xml. In this file we define a package named dates and mapped under <context-root>/dates/* URL.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <package name="dates" namespace="/dates" extends="struts-default">
    <action name="CurrentDate" class="com.tzavellas.dates.web.CurrentDateAction">
      <result>/WEB-INF/jsp/date.jsp</result>
    </action>
    <!-- Add more actions here -->
  </package>
</struts>

The package contains our only action, named CurrentDate and mapped to the URL <context-root>/dates/CurrentDate.action.

5. Create the welcome file

Now we will create our welcome file that redirects the user to the Struts action. This is a simple HTML page named index.html (as defined in web.xml) and located under the context root. The page uses a meta tag to redirect to the URL of the action .

<html>
  <head>
    <meta http-equiv="Refresh" content="0;URL=dates/CurrentDate.action">
  </head>
  <body>
    <p>Loading ...</p>
  </body>
</html>

6. Code the action

Finally it’s time for some Java code. The below code is a simple Struts 2 action that when called will set the value of the currentDate property to the current date.

package com.tzavellas.dates.web;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;

public class CurrentDateAction extends ActionSupport {

  private Date currentDate;

  @Override
  public String execute() throws Exception {
    currentDate = new Date();
    return SUCCESS;
  }

  public Date getCurrentDate() {
    return currentDate;
  }
}

Note that unlike Servlets or Struts 1 actions, in Struts 2 for every HTTP request a new action instance is created so it is safe to mutate an action property (like the currentDate above) with request specific data.

7. Create the view

As we defined in the dates package (dates.xml) the view for the CurrentDateAction is a JSP file localed in WEB-INF/jsp/date.jsp. The below code, for the date.jsp page, uses the Struts 2 tag library to display the value of the currentDate property of the action.

<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>The current date</title>
  </head>
  <body>
    <h1>The current date is: <s:property value="currentDate"/></h1>
  </body>
</html>

We’ve just created a simple application with Struts 2. In the next section we are going to define a stateless session EJB3 and wire it with the above action using Guice.

For more information about the Struts 2 web framework visit the Struts 2 wiki pages.

The EJB and the integration with Guice

8. Create the stateless session EJB3

With your favorite IDE add an EJB module to the enterprise project we created in step 1.

Below we define the SLSB with a remote interface and one method that returns the current date. The bean is mapped to the global JNDI name com.tzavellas.dates.ejb.DatesManagerBean.

package com.tzavellas.dates.ejb;
import java.util.Date;
import javax.ejb.Stateless;

@Stateless(mappedName="com.tzavellas.dates.ejb.DatesManagerBean")
public class DatesManagerBean implements DatesManagerRemote {

  public Date currentDate() {
    return new Date();
  }
}
package com.tzavellas.dates.ejb;
import java.util.Date;
import javax.ejb.Remote;

@Remote
public interface DatesManagerRemote {
  Date currentDate();
}

9. Add the Guice jars in the classpath

Add guice-1.0.jar and guice-struts2-plugin-1.0.1.jar in WEB-INF/lib directory of your web module. The jar file guice-1.0.jar contains the core Guice implementation and the guice-struts2-plugin-1.0.1.jar file contains the Guice’s Struts 2 integration code.

10. Edit struts.xml to include the Guice plug-in

Struts 2 is a very flexible framework. One of Struts’ many extensions is the ObjectFactory plug-in interface. The responsibility of an ObjectFactory is to create the objects managed by Struts. An ObjectFactory is usually a dependency injection container like Spring, Pico and Guice.

To define Guice as the ObjectFactory of our Struts 2 application we have to set the struts.objectFactory property to guice in the struts.xml file and Guice will then be responsible for instantiating all the Struts managed objects (actions, interceptors, etc) .

To continue add the following lines in struts.xml.

<!-- Use Guice as the ObjectFactory for this application -->
<constant name="struts.objectFactory" value="guice" />
<!-- When wiring actions use Guice bindings defined in the below module -->
<constant name="guice.module" value="com.tzavellas.dates.web.EjbModule"/>

11. Code the EjbModule

In the above struts.xml we defined two properties, struts.objectFactory and guice.module. To explain the guice.module property and the concept of Guice modules we have to explain the basics of Guice.

Guice is a, Java 5 based, dependency injection container that does constructor, field and setter injection (Guice also has features like support for AOP Alliance interceptors that we are not going to talk about in this post). To configure Guice you create a set of modules. A module implements the com.google.inject.Module interface and contains bindings. Bindings are created with the com.google.inject.Binder that is passed to the configure(Binder) method of a module. A binding is a pair composed of a type (key) and an implementation. An implementation can be an object, a class or a provider (factory). The bindings are consulted by the Guice Injector when doing dependency injection.

In the Guice Struts 2 plug-in the Guice ObjectFactory creates an Injector that then reads the module from the guice.module property in the struts.xml file and uses the bindings that are specified in that module to do dependency injection in Struts 2 actions and interceptors.

All we have to do to enable our EJB to be injected into an action is to create a binding for the client interface of the bean. We can’t create a binding to a class or instance, because the EJB’s instances must be instantiated by the EJB container and not by Guice, so we will use a provider that will lookup the EJB from JNDI. The Guice library includes a JNDI provider that we are going to use that it is located in the com.google.inject.jndi.JndiIntegration class.

The below code is the implementation of the EJBModule, which has only two bindings. The first binds the javax.naming.Context type to the javax.naming.InitialContext implementation. This means that when the Guice Injector finds a field or parameter of type javax.naming.Context, that needs to be injected (marked with the @Inject annotation), it will create a new object of type javax.naming.InitialContext and inject it. This binding is needed by the JNDI provider that we are going to use in the next binding.

The second binding binds our EJB’s remote interface to the JNDI provider. The JNDI provider is returned from the call to the static JndiIntegration.fromJndi(Class, String) method. To get a JNDI provider we have to specify the expected class and JNDI name. This binding tells the Guice Injector that when it finds a field or parameter of type com.tzavellas.dates.ejb.DatesManagerRemote, that needs to be injected (marked with the @Inject annotation), it should call the provider’s get() method to retrieve an instance to inject.

package com.tzavellas.dates.web;
import com.google.inject.Binder;
import com.google.inject.Module;
import static com.google.inject.jndi.JndiIntegration.fromJndi;
import com.tzavellas.dates.ejb.DatesManagerRemote;
import javax.naming.Context;
import javax.naming.InitialContext;

public class EjbModule implements Module {

  public void configure(Binder binder) {
    // Bind Context to the default InitialContext.
    binder.bind(Context.class).to(InitialContext.class);
    // Bind the remote interface to the JNDI name using the JNDI Provider
    binder.bind(DatesManagerRemote.class)
          .toProvider(fromJndi(DatesManagerRemote.class, "com.tzavellas.dates.ejb.DatesManagerBean"));
  }
}

For more information on how to do dependency injection with Guice see the Guice User’s Guide.

12. Change the action to use the EJB

Now that Guice instantiates our actions we can use the normal Guice @Inject annotation to mark an injection point in the action class. We can use any of the constructor, setter and field injection mechanisms. The below code uses field injection because it might be more familiar to EJB3 developers.

package com.tzavellas.dates.web;
import com.google.inject.Inject;
import com.opensymphony.xwork2.ActionSupport;
import com.tzavellas.dates.ejb.DatesManagerRemote;
import java.util.Date;

public class CurrentDateAction extends ActionSupport {
  // Guice field injection of the SLSB
  @Inject DatesManagerRemote bean;

  private Date currentDate;

  @Override
  public String execute() throws Exception {
    currentDate = bean.currentDate();
    return SUCCESS;
  }

  public Date getCurrentDate() {
    return currentDate;
  }
}

Conclusion

We are done. We’ve just coded a simple Struts 2 application that uses Guice to inject stateless session EJB3s to Struts actions. You can follow the instructions outlined above to do the same into your applications.

Appendix: Quick summary of all the steps

Assuming that you have a working Struts 2 application, below you will find a series of steps you could follow to do dependency injection of your stateless EJB3s into your Struts 2 actions.

For your project:

  1. Include the Guice jars in the WEB-INF/lib directory.
  2. Define a Guice module that will contain the bindings for your EJBs.
  3. Edit the struts.xml to define Guice as your ObjectFactory and include the above module.

For every EJB that you want to inject into your Struts actions:

  1. Inside the module, define a binding for the EJB using the Guice Provider from com.google.inject.jndi.JndiIntegration class, by specifying the bean’s client interface and the global JNDI name of the bean (or an ejb-ref if you have one defined in web.xml).
  2. Use the @Inject annotation in the Struts actions where you want the EJBs injected.