Spring can be easily integrated into any Java-based web framework. All you need to dois to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation <context-param> to set which context files to load.
NOTE: Listeners were added to the Servlet API in version 2.3. If you have a Servlet 2.2 container, you can use the ContextLoaderServlet to achieve this same functionality.
If you don't specify the contextConfigLocation context parameter, the ContextLoaderListener will look for a /WEB-INF/applicationContext.xml file to load. Once the context files are loaded, Spring creates a WebApplicationContext object based on the bean definitions and puts it into the ServletContext.
All Java web frameworks are built on top of the Servlet API, so you can use the following code to get the ApplicationContext that Spring created.
The WebApplicationContextUtils classisfor convenience, so you don't have to remember the name of the ServletContext attribute. Its getWebApplicationContext() method will return null if an object doesn't exist under the WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE key. Rather than risk getting NullPointerExceptions in your application, it's better to use the getRequiredWebApplicationContext() method. This method throws an Exception when the ApplicationContext is missing.
Once you have a reference to the WebApplicationContext, you can retrieve beans by their name or type. Most developers retrieve beans by name, then cast them to one of their implemented interfaces.
Fortunately, most of the frameworks inthis section have simpler ways of looking up beans. Not only do they make it easy to get beans from the BeanFactory, but they also allow you to use dependency injection on their controllers. Each framework section has more detail on its specific integration strategies.
14.2. JavaServer Faces
JavaServer Faces (JSF) is a component-based, event-driven web framework. According to Sun Microsystem's JSF Overview, JSF technology includes:
A set of APIs for representing UI components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility.
A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page.
14.2.1. DelegatingVariableResolver
The easiest way to integrate your Spring middle-tier with your JSF web layer is to use the DelegatingVariableResolver class. To configure this variable resolver in your application, you'll need to edit your faces-context.xml. After the opening <faces-config> element, add an <application> element and a <variable-resolver> element within it. The value of the variable resolver should reference Spring's DelegatingVariableResolver:
By specifying Spring's variable resolver, you can configure Spring beans as managed properties of your managed beans. The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's root WebApplicationContext. This allows you to easily inject dependencies into your JSF-managed beans.
Managed beans are defined in your faces-config.xml file. Below is an example where #{userManager} is a bean that's retrieved from Spring's BeanFactory.
The DelegatingVariableResolver is the recommended strategy for integrating JSF and Spring. If you're looking for more robust integration features, you might take a look at the JSF-Spring project.
14.2.2. FacesContextUtils
A custom VariableResolver works well when mapping your properties to beans in faces-config.xml, but at times you may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It's similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.
Struts is the de facto web framework for Java applications, mainly because it was one of the first to be released (June 2001). Invented by Craig McClanahan, Struts is an open source project hosted by the Apache Software Foundation. At the time, it greatly simplified the JSP/Servlet programming paradigm and won over many developers who were using proprietary frameworks. It simplified the programming model, it was open source, and it had a large community, which allowed the project to grow and become popular among Java web developers.
To integrate your Struts application with Spring, you have two options:
Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.
14.3.1. ContextLoaderPlugin
The ContextLoaderPlugin is a Struts 1.1+ plug-in that loads a Spring context file for the Struts ActionServlet. This context refers to the root WebApplicationContext (loaded by the ContextLoaderListener) as its parent. The default name of the context file is the name of the mapped servlet, plus -servlet.xml. If ActionServlet is defined in web.xml as <servlet-name>action</servlet-name>, the defaultis /WEB-INF/action-servlet.xml.
To configure this plug-in, add the following XML to the plug-ins section near the bottom of your struts-config.xml file:
It is possible to use this plugin to load all your context files, which can be useful when using testing tools like StrutsTestCase. StrutsTestCase's MockStrutsTestCase won't initialize Listeners on startup so putting all your context files in the plugin is a workaround. A bug has been filed forthis issue.
After configuring this plug-inin struts-config.xml, you can configure your Action to be managed by Spring. Spring 1.1.3 provides two ways to dothis:
Override Struts' default RequestProcessor with Spring's DelegatingRequestProcessor.
Use the DelegatingActionProxy classin the type attribute of your <action-mapping>.
Both of these methods allow you to manage your Actions and their dependencies in the action-context.xml file. The bridge between the Action in struts-config.xml and action-servlet.xml is built with the action-mapping's "path" and the bean's "name". If you have the following in your struts-config.xml file:
<action path="/users" .../>
You must define that Action's bean with the "/users" name in action-servlet.xml:
<bean name="/users" .../>
14.3.1.1. DelegatingRequestProcessor
To configure the DelegatingRequestProcessor in your struts-config.xml file, override the "processorClass" property in the <controller> element. These lines follow the <action-mapping> element.
After adding this setting, your Action will automatically be looked up in Spring's context file, no matter what the type. In fact, you don't even need to specify a type. Both of the following snippets will work:
If you're using Struts' modules feature, your bean names must contain the module prefix. For example, an action defined as <action path="/user"/> with module prefix "admin" requires a bean name with <bean name="/admin/user"/>.
NOTE: If you're using Tiles in your Struts application, you must configure your <controller> with the DelegatingTilesRequestProcessor.
14.3.1.2. DelegatingActionProxy
If you have a custom RequestProcessor and can't use the DelegatingTilesRequestProcessor, you can use the DelegatingActionProxy as the type in your action-mapping.
The bean definition in action-servlet.xml remains the same, whether you use a custom RequestProcessor or the DelegatingActionProxy.
If you define your Action in a context file, the full feature set of Spring's bean container will be available for it: dependency injection as well as the option to instantiate a new Action instance for each request. To activate the latter, add singleton="false" to your Action's bean definition.
As previously mentioned, you can retrieve the WebApplicationContext from the ServletContext using the WebApplicationContextUtils class. An easier way is to extend Spring's Action classes for Struts. For example, instead of subclassing Struts' Action class, you can subclass Spring's ActionSupport class.
The ActionSupport class provides additional convenience methods, like getWebApplicationContext(). Below is an example of how you might use thisin an Action:
Spring includes subclasses for all of the standard Struts Actions - the Spring versions merely have Support appended to the name:
ActionSupport,
DispatchActionSupport,
LookupDispatchActionSupport and
MappingDispatchActionSupport.
The recommended strategy is to use the approach that best suits your project. Subclassing makes your code more readable, and you know exactly how your dependencies are resolved. However, using the ContextLoaderPlugin allow you to easily add new dependencies in your context XML file. Either way, Spring provides some nice options for integrating the two frameworks.
14.4. Tapestry
Tapestry is a powerful, component-oriented web application framework from Apache's Jakarta project (http://jakarta.apache.org/tapestry). While Spring has its own powerful web ui layer, there are a number of unique advantages to building a J2EE application using a combination of Tapestry for the web ui, and the Spring container for the lower layers. This document attempts to detail a few best practices for combining these two frameworks. It is expected that you are relatively familiar with both Tapestry and Spring Framework basics, so they will not be explained here. General introductory documentation for both Tapestry and Spring Framework are available on their respective web sites.
14.4.1. Architecture
A typical layered J2EE application built with Tapestry and Spring will consist of a top UI layer built with Tapestry, and a number of lower layers, hosted out of one or more Spring Application Contexts.
User Interface Layer:
- concerned with the user interface
- contains some application logic
- provided by Tapestry
- aside from providing UI via Tapestry, code inthis layer does its work via objects which implement interfaces from the Service Layer. The actual objects which implement these service layer interfaces are obtained from a Spring Application Context.
Service Layer:
- application specific 'service' code
- works with domain objects, and uses the Mapper API to get those domain objects into and out of some sort of repository (database)
- hosted in one or more Spring contexts
- code inthis layer manipulates objects in the domain model, in an application specific fashion. It does its work via other code inthis layer, and via the Mapper API. An objectinthis layer is given the specific mapper implementations it needs to work with, via the Spring context.
- since code inthis layer is hosted in the Spring context, it may be transactionally wrapped by the Spring context, as opposed to managing its own transactions
Domain Model:
- domain specific object hierarchy, which deals with data and logic specific to this domain
- although the domain object hierarchy is built with the idea that it is persisted somehow and makes some general concessions to this (for example, bidirectional relationships), it generally has no knowledge of other layers. As such, it may be tested in isolation, and used with different mapping implementations for production vs. testing.
- these objects may be standalone, or used in conjunction with a Spring application context to take advantage of some of the benefits of the context, e.g., isolation, inversion of control, different strategy implementations, etc.
Data Source Layer:
- Mapper API (also called Data Access Objects): an API used to persist the domain model to a repository of some sort (generally a DB, but could be the filesystem, memory, etc.)
- Mapper API implementations: one or more specific implementations of the Mapper API, for example, a Hibernate-specific mapper, a JDO-specific mapper, JDBC-specific mapper, or a memory mapper.
- mapper implementations live in one or more Spring Application Contexts. A service layer objectis given the mapper objects it needs to work with via the context.
Database, filesystem, or other repositories:
- objects in the domain model are stored into one or more repositories via one or more mapper implementations
- a repository may be very simple (e.g. filesystem), or may have its own representation of the data from the domain model (i.e. a schema in a db). It does not know about other layers howerver.
14.4.2. Implementation
The only real question (which needs to be addressed by this document), is how Tapestry pages get access to service implementations, which are simply beans defined in an instance of the Spring Application Context.
14.4.2.1. Sample application context
Assume we have the following simple Application Context definition, in xml form:
Inside the Tapestry application, we need to load this application context, and allow Tapestry pages to get the authenticationService and userService beans, which implement the AuthenticationService and UserService interfaces, respectively.
14.4.2.2. Obtaining beans in Tapestry pages
At this point, the application context is available to a web application by calling Spring's static utility function WebApplicationContextUtils.getApplicationContext(servletContext), where servletContext is the standard ServletContext from the J2EE Servlet specification. As such, one simple mechanism for a page to get an instance of the UserService, for example, would be with code such as:
This mechanism does work. It can be made a lot less verbose by encapsulating most of the functionality in a method in the baseclassfor the page or component. However, in some respects it goes against the Inversion of Control approach which Spring encourages, which is being used in other layers of this app, in that ideally you would like the page to not have to ask the context for a specific bean by name, and in fact, the page would ideally not know about the context at all.
Luckily, there is a mechanism to allow this. We rely upon the fact that Tapestry already has a mechanism to declaratively add properties to a page, and it isin fact the preferred approach to manage all properties on a page inthis declarative fashion, so that Tapestry can properly manage their lifecycle as part of the page and component lifecycle.
14.4.2.3. Exposing the application context to Tapestry
First we need to make the ApplicationContext available to the Tapestry page or Component without having to have the ServletContext; thisis because at the stage in the page's/component's lifecycle when we need to access the ApplicationContext, the ServletContext won't be easily available to the page, so we can't use WebApplicationContextUtils.getApplicationContext(servletContext) directly. One way is by defining a custom version of the Tapestry IEngine which exposes thisfor us:
// insert ApplicationContext in global, if not there
Map global = (Map) getGlobal();
ApplicationContext ac = (ApplicationContext) global.get(APPLICATION_CONTEXT_KEY);
if (ac == null) {
ac = WebApplicationContextUtils.getWebApplicationContext(
context.getServlet().getServletContext()
);
global.put(APPLICATION_CONTEXT_KEY, ac);
}
}
}
This engine class places the Spring Application Context as an attribute called "appContext"inthis Tapestry app's 'Global' object. Make sure to register the fact that this special IEngine instance should be used forthis Tapestry application, with an entry in the Tapestry application definition file. For example:
Now in our page or component definition file (*.page or *.jwc), we simply add property-specification elements to grab the beans we need out of the ApplicationContext, and create page or component properties for them. For example:
The OGNL expression inside the property-specification specifies the initial value for the property, as a bean obtained from the context. The entire page definition might look like this:
Now in the Java class definition for the page or component itself, all we need to dois add an abstract getter method for the properties we have defined, to access them. When the page or component is actually loaded by Tapestry, it performs runtime code instrumentation on the classfile to add the properties which have been defined, and hook up the abstract getter methods to the newly created fields. For example:
// our UserService implementation; will come from page definition
publicabstract UserService getUserService();
// our AuthenticationService implementation; will come from page definition
In this example, we've managed to allow service beans defined in the Spring ApplicationContext to be provided to the page in a declarative fashion. The page class does not know where the service implementations are coming from, and in fact it is easy to slip in another implementation, for example, during testing. This inversion of control is one of the prime goals and benefits of the Spring Framework, and we have managed to extend it all the way up the J2EE stack inthis Tapestry application.
14.5. WebWork
WebWork is a web framework designed with simplicity in mind. It's built on top of XWork, which is a generic command framework. XWork also has an IoC container, but it isn't as full-featured as Spring and won't be covered inthis section. WebWork controllers are called Actions, mainly because they must implement the Action interface. The ActionSupport class implements thisinterface, and it is most common parent classfor WebWork actions.
WebWork maintains its own Spring integration project, located on java.net in the xwork-optional project. Currently, three options are available for integrating WebWork with Spring:
SpringObjectFactory: override XWork's default ObjectFactory so XWork will look for Spring beans in the root WebApplicationContext.
ActionAutowiringInterceptor: use an interceptor to automatically wire an Action's dependencies as they're created.
SpringExternalReferenceResolver: look up Spring beans based on the name defined in an <external-ref> element of an <action> element.
All of these strategies are explained in further detail in WebWork's Documentation.