Spring MVC 3, JSF 2 with Maven 2 and Tomcat 7

So, recently I started on a little hobby-project and I wanted to see if I could harness the strengths of Spring MVC together with JSF 2 and run it all on Tomcat 7. The reasons for these are several:

  • I wanted a combined template and component-oriented approach to view construction. Granted, there are numerous different frameworks out there that does this, but I wanted to try out JSF 2 as it seems to accomplish these things in a fairly easy and concise way.
  • I don’t care much for the request handling pattern and URL scheme that JSF brings with it. Call me conservative, but I like a clean MVC pattern with a clear division of roles. Most component-based frameworks, in my opinion, blur the lines unduly between controller and view. I’m typically not very fond of automagic form generation and post-back and the whole “code behind” concept that JSF (and Tapestry and ASP.NET and a bunch of other component frameworks) use. So, Spring MVC is more my style. There are other action-oriented frameworks you can use, but Spring MVC is as good as any plus…
  • …I’m not to eager to go the full JEE CDI approach. Spring can still offers most of what JEE’s got and it’s definitely got everything I need. It also has some things that JEE is still lacking, for example AOP support. With Spring’s support for JPA, the circle is complete and CDI is out.
  • Since I don’t need the full JEE package, I can deploy it all in my favorite light-weight container, Tomcat. Yay!
  • Since I prefer to write most of my client-side code myself (using either Prototype/Scriptaculous or jQuery), I typically fore go using pre-built component frameworks (PrimeFaces et al). In my experience, they tend to deliver almost what you want, but never exactly. And when you run into situations and cases that aren’t covered by the framework, you’ll start to work against it instead of with it, which usually ends up burning more time than just doing it yourself.

You’d think that all this would be a walk in the park. I mean, it’s two of the largest and most established frameworks – there should be no problems bridging the two, right? Well, it turns out it’s still a bit tricky…

The major obstacles that you have to get around are

  1. Exposing Spring beans to the JSF pages.
  2. Using JSF pages as views in a Spring MVC request.
  3. Maintaining the JSF resource handling intact
  4. Maintaining support for JSF form handling (h:form, h:commandButton etc)

Number 4, i found, is very tricky to accomplish. It would require hooking in a lot of custom handling into the JSF framework. However, like I stated previously, I don’t even want the whole automagical form madness. I wan’t clean forms I have full control over myself (sometimes I want regular posts, sometimes I want AJAX posts with HTML fragment responses, sometimes I want AJAX posts with JSON responses), and I want them to post to my own Spring MVC controllers. With all that in mind, I completely dropped trying to get JSF h:form to work. If you can’t live without that, this might not be for you.

So, without further ado I’ll just go ahead and show you my various configurations.

Directory layout

Standard maven 2 layout, with JSF conventions applied

- src/
  - main/
    - java/ (Java sources
    - resources/
      - applicationContext.xml (spring config)
      - log4j.properties (log4j config)
      - MessageResources.properties (JSF message resources)
      - META-INF/
        - persistence.xml (JPA config)
    - webapp/
      - resources/ (all static resources go in this directory, as per JSF convention)
      - WEB-INF/
        - faces-config.xml (JSF config)
        - web.xml (web config)
        - templates/ (all JSF templates go in this directory)
        - views/ (all JSF views go in this directory)


The maven config is fairly standard. As you might notice, I’m using the reference implementation of JSF 2 here (Mojarra). If you plan to deploy this to a JEE container (JBoss etc), you should mark them as “provided” to prevent conflicts. You might also notice I’m including spring-webflow. I’m not planning to use anything related to webflow as such, but that module includes the class JsfView that is required when configuring Spring MVC to use JSF views. You could strip that class out and clean it up from webflow dependencies, but I couldn’t be bothered yet.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">




No mysteries here, just bootstrap spring and JSF, make Spring handle everything except .jsf requests (this is so the JSF resource handling will still work, more on that further down).

    <servlet-name>Faces Servlet</servlet-name>
    <servlet-name>Faces Servlet</servlet-name>


<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"


The SpringBeanFacesELResolver is the glue that allows JSF pages to use Spring beans is if they were @ManagedBeans. In our scenario here, I’m completely ignoring to use @ManagedBean. Instead, I’m using spring beans and spring scopes.

The CustomResourceHandler is something I wrote to allow the JSF resource handler to function properly. This is needed if you want JSF tags like h:outputScript, h:outputStylesheet and h:graphicImage to work (served from the webapp/resources directory).


package helloworld.faces.application;

import javax.faces.application.Resource;
import javax.faces.application.ResourceHandler;
import javax.faces.application.ResourceHandlerWrapper;
import javax.faces.application.ResourceWrapper;
import javax.faces.context.FacesContext;

import com.sun.faces.util.Util;

 * Custom JSF ResourceHandler.
 * This handler bridges between Spring MVC and JSF managed resources. The handler takes
 * care of the case when a JSF facelet is used as a view by a Spring MVC Controller and the
 * view uses components like h:outputScript and h:outputStylesheet by correctly pointing the 
 * resource URLs generated to the JSF resource handler.
 * The reason this custom handler wrapper is needed is because the JSF internal logic assumes
 * that the request URL for the current page/view is a JSF url. If it is a Spring MVC request, JSF
 * will create URLs that incorrectly includes the Spring controller context.
 * This handler will strip out the Spring context for the URL and add the ".jsf" suffix, so the
 * resource request will be routed to the FacesServlet with a correct resource context (assuming the
 * faces servlet is mapped to the *.jsf pattern). 
public class CustomResourceHandler extends ResourceHandlerWrapper {

    private ResourceHandler wrapped;
    public CustomResourceHandler(ResourceHandler wrapped) {
        this.wrapped = wrapped;
    public ResourceHandler getWrapped() {
        return this.wrapped;    
    public Resource createResource(String resourceName, String libraryName) {
        return new CustomResource(super.createResource(resourceName, libraryName));
    public Resource createResource(String resourceName, String libraryName,
            String contentType) {
        return new CustomResource(super.createResource(resourceName, libraryName, contentType));
    private static class CustomResource extends ResourceWrapper {

        private Resource wrapped;
        private CustomResource(Resource wrapped) {
            this.wrapped = wrapped;
        public Resource getWrapped() {
            return this.wrapped;
        public String getRequestPath() {
            String path = super.getRequestPath();
            FacesContext context = FacesContext.getCurrentInstance();
            String facesServletMapping = Util.getFacesMapping(context);
            // if prefix-mapped, this is a resource that is requested from a faces page
            // rendered as a view to a Spring MVC controller.
            // facesServletMapping will, in fact, be the Spring mapping
            if (Util.isPrefixMapped(facesServletMapping)) {
                // remove the Spring mapping
                path = path.replaceFirst("(" + facesServletMapping + ")/", "/");
                // append .jsf to route this URL to the FacesServlet
                path = path.replace(wrapped.getResourceName(), wrapped.getResourceName() + ".jsf");
            return path;


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

    <context:component-scan base-package="helloworld" />
    <!-- map all requests to /resources/** to the container default servlet (ie, don't let Spring handle them) -->
    <bean id="defaultServletHttpRequestHandler" class="org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler" />
    <bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="urlMap">
            <entry key="/resources/**" value-ref="defaultServletHttpRequestHandler" />
    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" />
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="cache" value="false" />
        <property name="viewClass" value="org.springframework.faces.mvc.JsfView" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".xhtml" />

Important things to note here is the view resolver that uses the JsfView viewClass. Like I mentioned, this class lives in the spring-faces module in spring webflow. The three beans defined above are to allow static resources to be served outside of Spring. Since I mapped the DispatcherServlet in web.xml to the “/” url-pattern, Spring will effectivly take over all request handling. The DefaultServletHttpRequestHandler is a handler that will defer handling to the container default handler (ie Tomcats default servlet). My simpleUrlHandlerMapping maps all requests to /resources/** to the default handler and finally you need to create and adapter (HttpRquestHandlerAdapter) that can work with the handler. All this will allow me to access static resources under the /resources folder using normal linking. I mentioned above that my custom resource handler allowed me to access them using JSF tags like h:graphicImage. This is for when I want to access them using a regular img, script or link tag.

Hello World example

This short example consists of 2 java classes (controller and model) and one JSF xhtml page (view).

HelloWorld (request-scoped model bean>

package helloworld;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

@Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class HelloWorld {
    private String message;

    public String getMessage() {
        return message;

    public void setMessage(String message) {
        this.message = message;

HelloWorldController (controller)

package helloworld;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

public class HelloWorldController {

	private HelloWorld helloWorld;
	@RequestMapping(value="/helloWorld", method=RequestMethod.GET)
	public void helloWorld() {
		helloWorld.setMessage("Hello World from Spring MVC to JSF");
	@RequestMapping(value="/helloWorld", method=RequestMethod.POST)
	public void helloWorldPost(@RequestParam String msg) {

helloWorld.xhtml (JSF view, goes under WEB-INF/views

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="http://www.w3.org/1999/xhtml"
        <title>Hello World</title>
        <p>Say something: </p>
        <form method="post">
            <input name="msg" type="text"></input>
            <input type="submit" ></input>
        <p>This image is linked as a JSF resource</p>
        <h:graphicImage name="images/jsf.jpg" />
        <p>This image is directly linked</p>
        <img src="resources/images/spring.png"></img>

As you can see, this page demonstrates how to access a Spring bean using JSF EL (${helloWorld.message}) and how to render an image both using JSF resources handling and a regular img tag. You will have to manually put some images in the webapp/resources/images folder to try this.
Posting the form should reload the page and display the message you entered in the textbox.


Spring 3.0 and @Cacheable with a Warning!

Many systems (and developers, myself included) have come to rely heavily on the Spring method caching provided by the (now deprecated) spring-modules-cache (https://springmodules.dev.java.net/docs/reference/0.8/html/cache.html) add-on, providing an annotation-driven integration of various caching-frameworks (including ehcache) through the @Cacheable annotation.

Recently, I was involved in upgrading a large Spring-driven website from Spring 2.5 to Spring 3.0. During this we discovered that the method-caching support that was delivered through spring-modules-cache add-on (which we rely heavily on throughout our system) is not compatible with Spring 3. The new “Spring Extensions” (http://www.springsource.org/extensions/list) inititive from springsource have yet to include a replacement for this module. In the meantime, alternatives are available.

We ended up using the spring-ehcache-annotations projekt hosted at googlecode (http://code.google.com/p/ehcache-spring-annotations/ especially http://code.google.com/p/ehcache-spring-annotations/wiki/SwitchingFromSpringModules). The refactoring required was limited to changing the package include of the @Cacheable annotation and the cacheName attribute which the implementors of the project for some reason decided to have different than the spring-modules version.

However – and here comes the warning – while this seemed to work without any problems during testing, once in production we started noticing inconsistent behaviour of our system. Finally we managed to home in on the root-cause which turned out to be this new caching integration. As it turned out, we found serious flaws in the cache key generators in spring-ehcache-annotations. In the version we use (1.1.2), after some testing, we found that for methods with multiple parameters, we could get the default generator to produce identical keys for different combinations of input values. This is obviously a serious showstopper. The whole point of method-caching is to maintain unique cache records for each distinct combination of input values of your decorated methods. We ended up manually including the default cache-key generator from the old spring-modules-cache project and instructing spring-ehcache-annotations to use that instead. The following classes were required to include:

  • org.springmodules.cache.key.HashCodeCacheKeyGenerator
  • org.springmodules.cache.key.HashCodeCacheKey
  • org.springmodules.cache.key.HashCodeCalculator
  • org.springmodules.cache.util.Reflections
  • org.springmodules.util.Objects

NOTE: the HashCodeKeyGenerator has to be modified to implement com.googlecode.ehcache.annotations.key.CacheKeyGenerator instead of org.springmodules.cache.key.CacheKeyGenerator

In your spring-config, define bean for the “old” key generator

<!-- spring modules cache key generator -->
<bean name="springModulesHashCodeCacheKeyGenerator" class="org.springmodules.cache.key.HashCodeCacheKeyGenerator"/>

Then go ahead and override the default key generator in your spring config

<ehcache:annotation-driven default-cache-key-generator="springModulesHashCodeCacheKeyGenerator"/>

Annotation-driven aspects and Spring MVC

The built-in AspectJ support is a very strong selling-point for Spring and I’m a huge fan of aspect-oriented elegance. Generally though, I tend to approach it with what I consider to be a healthy dose of respect. It’s an immensly powerful tool, to be sure, but it also comes with the risk of making your system very hard to predict and to ultimately understand. Many IDE:s (like Eclipse) have good tooling available for resolving aspect applications at design-time, but it still makes it a lot more difficult for other programmers (and, ultimately, yourself) to reconstruct code-paths by just following method-calls.

One of my favourite patterns has become the annotation-driven aspect. Springs AspectJ supports pointcut declarations based on custom method or class annotations and to me, it’s the best of both worlds. Using annotations makes it clear which aspects are applied to which methods or classes, while at the same time giving you the non-intrusiveness if aspect oriented programming so you don’t have to rely on the tight coupling of inheritance or boiler-plate template code inside your methods.

When this pattern really comes to shine for me is in combination with Spring MVC. Even though request handlers in Spring MVC 2.5 are not forced to comply to a given interface, they nevertheless have a strong convention supported by the framework, ie a method returning a String, indicating a “redirect:” or a view mapping. Coupled together with the DispatcherServlets default behaviour of maintaining request attribute collections (and, by extension, the request itself) in a thread-local context, all relevant pieces of information are in place. So the basic pattern becomes:

  • A custom annotation and an aspect with a pointcut applied to all request handler methods with that annotation
  • An advise at that pointcut with the ability to access the current request parameters and modify it’s attributes, through the thread-local context
  • The ability to override which view or redirect to continue to before or after the controller
  • Any other processing you require

The same can be accomplished with interceptors, but due to the configuration limitation in Spring MVC, you can’t explicitly specify on a controller level which interceptors should be applied, so I find that the annotation-driven aspects becomes both clearer and much more flexible.

Other frameworks have different ways of enabling similar patterns. Struts 2 lets you specify the interceptor-stack by annotating your actions (in fact, it’s the core pattern of the entire framework). Many component-oriented frameworks (like Tapestry, Wicket, JSF etc) will give you secondary “hooks” into different steps of the component and request lifecycle where you can inject common functionality in a similar manner. With this pattern, you get the same power in Spring MVC.

A very simple example, a Trackable controller:

In this example, a controller wishes to register a request with some internal tracking service based on the existence of a cookie, whith the option of including a username, if one exists in the session.

First, the annotation:

public @interface Trackable {
   String trackAction();

Second, annotate your controller

public class SomeController {

   public String someUrlHandler() {
      return url;

Lastly, the aspect that binds it all together

public class TrackableAspect {
   private TrackingService trackingService;

   @Pointcut("@annotation(Trackable) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
   public void trackablePointcut() {

   public Object trackableAdvise(ProceedingJoinPoint pjp) {
      // RequestContextHolder managed by Spring MVC DispatcherServlet
      HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
      // Spring WebUtils
      Cookie cookie = WebUtils.getCookie(request, "trackingCookie");
      if (cookie != null) {
         // Get the trackAction specified on the annotation
         String trackAction = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(Trackable.class).trackAction();
         String trackingCode = cookieookie.getValue();
         String userName = request.getSession().getAttribute("userName");
         if (userName != null) {
            trackingService.trackLoggedInAction(trackAction, trackingCode, userName);
         } else {
            trackingService.trackAction(trackAction, trackingCode);
      // continue with normal execution
      return pjp.proceed();

As you can see, the around-advice will in this example always proceed with normal execution (ie, the @RequestMapping handler method) but there is nothing preventing you from ignoring normal execution in your advise and instead return some other value (which will then appear to the caller as the value returned from the advised method). As mentioned already, Spring MVC works on a convention-driven pattern so a handler method returning a String will forward execution to the view matching that string, or a String starting with “redirect:” will cause Spring MVC to send a client-side redirect response back to the browser.