Differences Between Interceptors and Filters in Spring MVC and Their Implementation

This article explains the conceptual differences between Spring MVC interceptors and servlet filters, demonstrates how to implement each with Java code, shows the necessary configuration in Spring and web.xml, and summarizes their respective use cases, lifecycles, and limitations for backend development.

Top Architect
Top Architect
Top Architect
Differences Between Interceptors and Filters in Spring MVC and Their Implementation

The article introduces the distinction between Interceptor and Filter in Java web applications, emphasizing that Interceptors work on action requests within the Spring MVC flow while Filters can intercept almost all requests, including static resources, before they reach the servlet container.

1. Difference between Interceptor and Filter

Interceptors operate between the Servlet and Controller layers, executing before and after controller methods, whereas Filters run after the request enters the Tomcat container but before any servlet processing, and also after the response leaves the servlet.

web.xml loading order: context‑param → listener → filter → servlet

2. Code Implementation

Interceptor

First, create a class that implements HandlerInterceptor and override its three methods:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // executed before controller method; return false to abort
    return false;
}

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

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    // executed after view rendering
}

A typical preHandle checks session information and redirects unauthenticated users:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (request.getSession().getAttribute("USERINFO") != null) {
        return true;
    }
    response.sendRedirect(request.getContextPath() + "/user/doLogin.do");
    return false;
}

Register the interceptor in Spring MVC configuration:

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

Filter

Create a class that implements javax.servlet.Filter:

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().indexOf("/user/doLogin.do") == -1) {
            response.sendRedirect(request.getContextPath() + "/user/doLogin.do");
            return;
        }
        filterChain.doFilter(request, response);
    }

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

Configure the filter in web.xml:

<!-- Configure custom filter for login control -->
<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

Both Interceptors and Filters embody AOP concepts for cross‑cutting concerns such as authentication, logging, and request preprocessing, but they differ in scope, lifecycle, and container dependency: Interceptors are Spring‑managed and can access the IoC container, while Filters are servlet‑spec defined and apply to all resource types.

Key differences include usage range (Interceptors can be used in web, application, or Swing layers; Filters are limited to web), configuration order (determined by web.xml), and lifecycle (Filters are instantiated once at container startup, Interceptors are created per Spring context).

Understanding when to use each mechanism helps developers design clean, maintainable backend architectures.

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.

JavaWeb DevelopmentInterceptorSpring MVCfilter
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

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.