Home » Java » Enterprise Java » Spring MVC Interceptors Example

About Roger Hughes

Roger Hughes

Spring MVC Interceptors Example

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

   * In this case intercept the request BEFORE it reaches the controller
  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

      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");
        "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 --> 
 <!-- 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:mapping path="/gb/shop/**"/>
  <bean class="marin.interceptor.RequestInitializeInterceptor" />

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.

Reference: Using Spring Interceptors in your MVC Webapp from our JCG partner Roger Hughes at the Captain Debug’s blog.

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

1 Comment on "Spring MVC Interceptors Example"

Notify of
Sort by:   newest | oldest | most voted
Binh Thanh Nguyen

Thanks, nice post