Advantages of spring interceptor over servlet filter
Even filters can do the same things that interceptors can but interceptors can do more easily and more elegantly.
 
Interceptors are more coupled to the request/response cycle than filters.
 
Can inject other beans in the interceptor.
 
Can use more advanced mapping patterns (ant-style).
 
You have the target handler object (controller) available, as well as the result ModelAndView object.
 
It is a bean, so you can use AOP with it.

 

 
The main advantage of spring framework HanderInterceptor is – that they can intercept between Controller Handling and View Rendering and they are spring Beans so it is easy to access another spring bean.
Servlet Filter vs Spring Interceptor

Servlet Filter and Spring Interceptors are important concepts in java world. But there is always confusion between both concepts. Both serve almost the same concept but there are differences when to use and for which purpose. 

 

Servlet Filter
Spring Interceptor
A Servlet Filter is used in the web layer only, you can’t use it outside of a web context.
Interceptors can be used anywhere.
For authentication of web pages, you would use a servlet filter.
Security stuff in your business layer or logging/bug tracking (a.k.a.
independent of the web layer) you would use an Interceptor.
For the Login authentication and auditing of incoming requests from web pages, we should use a servlet filter.
While for implementing your business layer logging and auditing and many other along feature we should use an Interceptor.
Filters implement javax.servlet.Filter
 Interceptors implement org.springframework.web.servlet.HandlerInterceptor

 

Further Reading

http://array151.com/blog/servlets/

http://array151.com/blog/servlet-filter/

http://array151.com/blog/spring-interceptors/

http://array151.com/blog/advantages-of-spring-interceptor-over-servlet-filter/

Spring Interceptors

Spring interceptors are for intercepting the controller methods. These are called before the control is passed to the controller method. You can intercept HTTP request and perform some actions on it and then hand over it to controller methods.You have to configure the interceptors in the project-servlet.xml.

Spring Interceptors can be used anywhere because it is defined in the Application context.

Spring interceptors can be used for security stuff in your business layer or logging or bug tracking that is independent of the web layer.

spring interceptor
  

Spring Interceptor – HandlerInterceptor

 
Three methods to implement spring interceptor
 
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler): used to intercept the request before it goes to handler method. This method returns the boolean value.
 
If true is returned, then request is processed through another spring interceptor or to send it to handler method if there are no further spring interceptors.
 
If false is returned, then there is no further processing of this request. Use response object to send response to the client request in this case.
Object handler is object to handle the request. Spring MVC Exception Handling can be used to handle exceptions if thrown and useful to send error page as response.
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView): method can be used to calculate the time taken by handler method to process the request. postHandle() as name suggests is called when HandlerAdapter has called the handler but Dispatcher Servlet still has to render the view.
 
ModelAndView object is injected to add additional attributes that can be used in the view page.
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex): as the name says this method is called after the view is rendered.
 

Interceptor Example:

 Calculate the execution time and save it into the ModelAndView object to display it on the page.

Spring Interceptors – Controller Class

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
publicclassHomeController{
      @RequestMapping(value =“/home”, method =RequestMethod.GET)
      publicString home(Model model){
            return“home”;
      }
}
 

Spring Interceptors – HandlerInterceptorAdapter

 
package com.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
public class RequestProcessingTimeInterceptor extends 
  HandlerInterceptorAdapter {
   @Override
   public boolean preHandle(HttpServletRequest request,
    HttpServletResponse response,Object handlerthrows Exception {
      long startTime = System.currentTimeMillis();
      System.out.println("Request URL ::" + request.getRequestURL()
          + " :: Start Time :: " + startTime);
      request.setAttribute("startTime", startTime);
      return true;
   }
   @Override
   public void preHandle(HttpServletRequest request, 
    HttpServletResponse response,Object handlerthrows Exception {
       
      long startTime = (long) request.getAttribute("startTime");
      System.out.println("Request URL :: " + 
         request.getRequestURL().toString() + " :: End time :: "
         + System.currentTimeMillis());
      System.out.println("Request URL :: " + 
         request.getRequestURL().toString() + " :: Time Taken :: "
         + (System.currentTimeMillis() - startTime));
      }
}
 

Spring Interceptor : dispatcher-servlet.xml Configuration

 
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:beans="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/mvc 
   http://www.springframework.org/schema/mvc/spring-mvc.xsd
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context.xsd">
  <annotation-driven/>
  <beans:bean
     class="org.springframework.web.servlet.view.
                                    InternalResourceViewResolver">
     <beans:propertyname="prefix"value="/WEB-INF/views/"/>
     <beans:propertyname="suffix"value=".jsp"/>
  </beans:bean>
  <!-- Configuring interceptors based on URI -->
  <interceptors>
     <interceptor>
     <mapping path="/*"/>
     <beans:bean 
         class="com.web.controller.RequestProcessingTimeInterceptor">
     </beans:bean>
  </interceptor>
</beans:beans>
en_USEnglish
en_USEnglish