Interceptor vs Filter in Spring MVC: Key Differences, Code Samples, and Usage Guide

This article explains the fundamental differences between Spring MVC interceptors and servlet filters, provides complete Java code examples for both, shows how to configure them in Spring and web.xml, and summarizes when to choose each approach for request handling and AOP-like functionality.

Architect
Architect
Architect
Interceptor vs Filter in Spring MVC: Key Differences, Code Samples, and Usage Guide

Interceptor vs Filter: Core Differences

In Spring MVC, an interceptor (implementing HandlerInterceptor) only intercepts action requests (the controller layer), while a filter (implementing javax.servlet.Filter) can intercept virtually all requests, including static resources such as CSS, JS, and images.

Interceptors run between the Servlet and the Controller, whereas filters run after the request enters the servlet container but before it reaches any servlet.

1. Interceptor Implementation

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // Executed before the controller method. Return false to abort processing.
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    // Executed after the controller method but before view rendering.
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    // Executed after the view has been rendered and the response is returned.
}

Typical configuration in spring-mvc.xml:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <mvc:exclude-mapping path="/user/doLogin.do"/>
        <bean class="net.zjitc.interceptor.LoginInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

2. Filter Implementation

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization logic
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getSession().getAttribute("USERINFO") == null && !request.getRequestURI().contains("/user/doLogin.do")) {
            response.sendRedirect(request.getContextPath() + "/user/doLogin.do");
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // Cleanup logic
    }
}

Corresponding web.xml configuration:

<filter>
    <filter-name>sessionFilter</filter-name>
    <filter-class>net.zjitc.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>sessionFilter</filter-name>
    <url-pattern>/pages/*</url-pattern>
    <url-pattern>/css/*</url-pattern>
    <url-pattern>/img/*</url-pattern>
    <url-pattern>/failer.jsp</url-pattern>
</filter-mapping>

3. Summary of Differences

Scope: Interceptors work in the Spring container and can be used in web, application, or Swing programs; filters are defined by the Servlet specification and only work in web applications.

Dependency: Interceptors are Spring‑specific; filters depend on the servlet container.

Target: Interceptors intercept only action (controller) requests; filters can intercept any request, including static resources.

Access: Interceptors can access the action context and value stack; filters cannot.

Lifecycle: Interceptors may be invoked multiple times during an action's lifecycle; a filter is instantiated once per container lifecycle.

Bean Injection: Interceptors can obtain Spring beans (e.g., services) via IoC; filters cannot directly access the Spring context.

Both mechanisms are implementations of the AOP (Aspect‑Oriented Programming) concept, enabling cross‑cutting concerns such as authentication, logging, and request preprocessing.

Interceptor vs Filter diagram
Interceptor vs Filter diagram
Filter chain illustration
Filter chain illustration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaaopWeb DevelopmentInterceptorSpring MVCfilter
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.