Spring MVC Interceptor vs Filter: Key Differences and Execution Order
This article explains the fundamental differences between Spring MVC interceptors and servlet filters—including definition, scope, configuration, lifecycle, and execution timing—and details their processing order with illustrative code samples and a request flow diagram.
In Spring MVC applications, interceptors and filters are common mechanisms for handling HTTP requests and responses. Although they share some similarities, they differ significantly in design, scope, configuration, lifecycle, and execution timing.
1. Differences between Interceptor and Filter
Definition: A filter is based on the Servlet specification and processes requests and responses at the container level. An interceptor is specific to the Spring MVC framework and processes logic before and after controller method execution.
Scope: Filters operate on all incoming requests across the entire application. Interceptors target only Spring MVC requests.
Configuration: Filters are configured in web.xml. Interceptors are configured via Java configuration or spring-servlet.xml.
Lifecycle: Filters are initialized when the servlet container starts and apply to the whole application. Interceptors are initialized within the Spring MVC application context and are effective only inside the DispatcherServlet.
Execution timing: Filters run before the request reaches the DispatcherServlet and after the response leaves it. Interceptors run at three points: preHandle (before controller), postHandle (after controller, before view), and afterCompletion (after view rendering).
2. Execution Order
Filter execution order: When a request enters the web application, it passes through the filter chain defined in web.xml. The order is determined by the <filter-mapping> entries, processing each filter sequentially until the request reaches the DispatcherServlet.
Interceptor execution order: Spring MVC interceptors are ordered by the HandlerInterceptor chain defined in configuration. Each interceptor executes its preHandle, then the controller, then postHandle, and finally afterCompletion. Multiple interceptors follow the order in which they are added.
Illustrative flow:
Request -> Filter1 -> Filter2 -> ... -> DispatcherServlet -> Interceptor1 (preHandle) -> Controller -> Interceptor1 (postHandle) -> Interceptor2 (preHandle) -> Controller -> Interceptor2 (postHandle) -> ViewResolver -> Response3. Code Examples
Filter implementation
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/somepath/*") // specify filter path
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// initialization
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// before controller
System.out.println("Filter is called before the request reaches the controller.");
// continue processing
chain.doFilter(request, response);
// after response
System.out.println("Filter is called after the response is generated.");
}
@Override
public void destroy() {
// cleanup
}
}Interceptor implementation
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// before controller
System.out.println("Interceptor - PreHandle: Before controller method.");
return true; // continue
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
// after controller, before view
System.out.println("Interceptor - PostHandle: After controller method.");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
// after view rendering
System.out.println("Interceptor - AfterCompletion: After view rendering.");
}
}Java configuration for interceptor
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/somepath/*");
}
}Conclusion
Filter: Based on the Servlet spec, executes earlier than the DispatcherServlet, suitable for application‑wide concerns such as encoding, authentication, and logging.
Interceptor: Spring MVC‑specific, runs around controller execution and can access MVC‑specific features like model data and view resolution.
Execution order: Filters run first; then the DispatcherServlet invokes interceptors. Choose filters for cross‑cutting, application‑level processing and interceptors for fine‑grained MVC request handling.
java1234
Former senior programmer at a Fortune Global 500 company, dedicated to sharing Java expertise. Visit Feng's site: Java Knowledge Sharing, www.java1234.com
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
