Wednesday, May 12, 2010

Interceptors in Spring MVC

These are different ways to configure Interceptors for Spring MVC based controllers.

1. If you have the URL / Controller mapping in xml you can define the interceptors as

<bean id="myService" class="com.test.services.MyService"/>

<bean id="myInterceptorOne" class="com.test.interceptors.FirstInterceptor">
<property name="myService" ref="myService" />
</bean>

<bean id="myInterceptorTwo" class="com.test.interceptors.SecondInterceptor" />

<bean id="defaultHandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

<bean name="/home.action" class="com.test.controller.FirstController"/>

<bean id="someId" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="myInterceptorOne"/>
<ref bean="myInterceptorTwo"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/index.action" value-ref="index"/>
</map>
</property>
</bean>

<bean id="index" class="com.test.controller.SecondController" />

I have defined 2 controllers. Only /index.action is intercepted by both the interceptors while /home.action is not.

2.Annotation-based controllers – you define the interceptors as –

<bean id="annotationMapper" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="myInterceptorOne"/>
<ref bean="myInterceptorTwo"/>
</list>
</property>
</bean>

The interceptors are applied to all the configured controllers.

3. While using annotation based controllers, we can use "mvc:interceptors" tag which can be used to define interceptors and control how they are applied.

Like

<mvc:interceptor>
<mvc:mapping path="/index.action"/>
<mvc:mapping path="/home.action"/>
<bean class="com.test.interceptors.ThirdInterceptor" />
</mvc:interceptor>

Here ThirdInterceptor would be applied to /index.action and /home.action

<mvc:interceptor>
<mvc:mapping path="/index.action"/>
<bean class="com.test.interceptors.ThirdInterceptor" />
</mvc:interceptor>

<mvc:interceptor>
<mvc:mapping path="/index.action"/>
<bean class="com.test.interceptors.FirstInterceptor" />
</mvc:interceptor>

Here ThirdInterceptor and FirstInterceptor (in the defined order) would be applied to /index.action.