Home > Uncategorized > Spring 3 MVC – Using mvc:interceptors

Spring 3 MVC – Using mvc:interceptors

One of the new feature in Spring 3 MVC  has been introduction of  mvc  XML configuration namespace that simplifies the setup of Spring MVC inside the web application.

Spring 3 allows you to intercept the request and response headers without writing the filter explicitly .  Spring’s handler mapping mechanism includes handler interceptors.

If you would prefer to write a filter explicitly, it has been covered in Servlet Filter to prevent No Cache.

From Spring MVC docs

Interceptors located in the handler mapping must implement HandlerInterceptor from the org.springframework.web.servlet package. This interface defines three methods: one is called before the actual handler is executed; one is called after the handler is executed; and one is called after the complete request has finished. These three methods should provide enough flexibility to do all kinds of preprocessing and postprocessing

You have an option in which instead of writing your own custom class, you can modify the servlet-Context.xml file to provide no caching feature

Here is what will go inside the file

<mvc:annotation-driven/>
<mvc:interceptors>
<bean id=”webContentInterceptor”>
<property name=”cacheSeconds” value=”0″/>
<property name=”useExpiresHeader” value=”true”/>
<property name=”useCacheControlHeader” value=”true”/>
<property name=”useCacheControlNoStore” value=”true”/>
</bean>
</mvc:interceptors>

I am giving the example of No cache but you can add any other property supported .

Remember, these settings will be done in your servlet-Context.xml and not in your application Context file.

The servlet-context.xml is set up when you are configuring the Displatcher Servlet

<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>

The only drawback is that it applies to all your requests and response . So if you would like to cache your images files, it would not allow even to do that.

When will this not work ?

If you are using any other filter mechanism outside Spring MVC , and your pages are not rendered through Dispatcher servlet, then this will not help you out. For eg the dispatcher servlet is configured to server pages behind folder foo/abc.htm, foo/faa/hello.html .

Now you have another set of pages outside foo like /index.html, /myDataView.jsp , then the above changes will not affect the response for these pages.

Reference : Spring 3 MVC docs

Categories: Uncategorized Tags:
  1. December 9th, 2014 at 08:45 | #1

    Please correct your configuration–>

  1. No trackbacks yet.