Using Spring Interceptors to Reuse Functionality

August 29, 2010

Spring MVC interceptors (learn more about interceptor design pattern here) can be used to plug in functionality that needs to be executed as part of handling a request. These interceptors can be an ideal place to reuse functionality that is applicable for non-web application related scenarios. Interceptors can be used to execute horizontal, cross cutting concerns – e.g. security, metrics, logging, etc. If you have an existing component that was developed for a command-line application or a JMS event handler and need to reuse it in a web app, an interceptor would be an ideal choice.

Here is an example implementation for a a Spring Interceptor extending the HandlerInterceptorAdapter:

package com.yourapp.learn;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
 Object handler) throws Exception {

 Boolean userAuthenticated = (Boolean)request.getSession().getAttribute("userAuthenticated");

 if (userAuthenticated) {
    return true;
 } else {
    return false;
 }

 }
}

This interceptor simply checks to see if the user is authenticated by looking for a session attribute. If the result is true, the request is processed further.
Here is an example bean definition fragment for utilizing the above:

<bean id="testInterceptor" />

<bean id="testSimpleUrlHandlerMapping"
 class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="interceptors">
 <list>
 <ref bean="testInterceptor"/>
 </list>
</property>

 <property name="mappings">
 <props>
 <prop key="/test">someController</prop>
 </props>
 </property>
</bean>

The actual logic can be in another component that is leveraged in the interceptor. The component itself could be reused across several apps. If such a component isn’t available, you can refactor existing logic to carve out the common functionality.


Follow

Get every new post delivered to your Inbox.