Tuesday, 27 September 2011

Using Spring Interceptors in your MVC Webapp

I thought that it was time to take a look at Spring’s MVC interceptor mechanism, which has been around for a good number of years and is a really useful tool.

A Spring Interceptor does what it says on the tin: intercepts an incoming HTTP request before it reaches your Spring MVC controller class, or conversely, intercepts the outgoing HTTP response after it leaves your controller, but before it’s fed back to the browser.

You may ask what use is this to you? The answer is that it allows you to perform tasks that are common to every request or set of requests without the need to cut ‘n’ paste boiler plate code into every controller class. For example, you could perform user authentication of a request before it reaches your controller and, if successful, retrieve some additional user details from a database adding them to the HttpServletRequest object before your controller is called. Your controller can then simply retrieve and use these values or leave them for display by the JSP. On the other hand, if the authentication fails, you could re-direct your user to a different page.

The demonstration code shows you how to modify the incoming HttpServletRequest object before it reaches your controller. This does nothing more than add a simple string to the request, but, as I said above, you could always make a database call to grab hold of some data that’s required by every request... you could even add some kind of optimization and do some caching at this point.

public class RequestInitializeInterceptor extends HandlerInterceptorAdapter {

 
// Obtain a suitable logger.
 
private static Log logger = LogFactory
      .getLog
(RequestInitializeInterceptor.class);

 
/**
   * In this case intercept the request BEFORE it reaches the controller
   */
 
@Override
 
public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler
) throws Exception {
   
try {

     
logger.info("Intercepting: " + request.getRequestURI());

     
// Do some changes to the incoming request object
     
updateRequest(request);

     
return true;
   
} catch (SystemException e) {
     
logger.info("request update failed");
     
return false;
   
}
  }

 
/**
   * The data added to the request would most likely come from a database
   */
 
private void updateRequest(HttpServletRequest request) {

   
logger.info("Updating request object");
    request.setAttribute
("commonData",
       
"This string is required in every request");
 
}

 
/** This could be any exception */
 
private class SystemException extends RuntimeException {

   
private static final long serialVersionUID = 1L;
   
// Blank
 
}
}

In the code above, I’ve chosen the simplest implementation method by extending the HandlerInterceptorAdaptor class, overriding preHandle(..) method. My preHandle(...) method does the error handling, deciding what to do if an error occurs and returning false if one does. In returning false the interceptor chain is broken and your controller class is not called. The actual business of messing with the request object is delegated to updateRequest(request).

The HandlerInterceptorAdaptor class has three methods, each of which are stubbed and, if desired, can be ignored. The methods are: prehandle(...), postHandle(...) and afterCompletion(...) and more information on these can be found in the Spring API documentation. Be aware that this can be somewhat confusing as the Handler Interceptor classes documentation still refer to MVC controller classes by their Spring 2 name of handlers. This point is easily demonstrated if you look at prehandle(...)’s third parameter of type Object and called handler. If you examine this in your debugger, you’ll see that it is an instance of your controller class. If you’re new to this technique, just remember that controller == handler.

The next step in implementing an interceptor is, as always, to add something to the Spring XML config file:

<!-- Configures Handler Interceptors --> 
<mvc:interceptors>  
 <!-- This bit of XML will intercept all URLs - which is what you want in a web app -->
 <bean class="marin.interceptor.RequestInitializeInterceptor" />
 
 <!-- This bit of XML will apply certain URLs to certain interceptors -->
 <!-- 
 <mvc:interceptor>
  <mvc:mapping path="/gb/shop/**"/>
  <bean class="marin.interceptor.RequestInitializeInterceptor" />
 </mvc:interceptor>
  -->
</mvc:interceptors>

The XML above demonstrates an either/or choice of adding an interceptor to all request URLs, or if you look at the commented out section, adding an interceptor to specific request URLs, allowing you to choose which URLs are connected to your interceptor class.

The eagle eyed readers may have noticed that the interceptor classes use inheritance and XML config as its method of implementation. In these days of convention over configuration, this pattern is beginning to look a little jaded and could probably do with a good overhaul. One suggestion would be to enhance the whole lot to use annotations, applying the same techniques that have already been added to the controller mechanism. This would add extra flexibility without the complication of using all the interfaces and abstract base classes. As a suggestion, a future interceptor class implementation could look something like this:

  @Intercept(value = "/gb/en/*", method = RequestMethod.POST)
 
public boolean myAuthenticationHandler(HttpServletRequest request,
      Model model
) {
   
// Put some code here
 
}

That concludes this look at Spring interceptors, it should be remembered that I’ve only demonstrated the most basic implementation - I may add extra examples another day...

3 comments:

Anonymous said...

Awesome explanation!

Neo said...

Nice article. Just a suggestion: you could add an example demonstrating how to use or access container managed beans in the interceptor. I think it's a common use case. A user-authentication example would be awesome.

Anonymous said...

Thanks,
Just the thing I was looking for.