Interceptor vs Filter in Java Web Applications: Concepts, Implementation, and Comparison

This article explains the differences between Spring MVC interceptors and servlet filters, provides complete Java code examples for both, describes how to configure them in Spring and web.xml, and summarizes their respective scopes, lifecycles, and typical use‑cases in web development.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Interceptor vs Filter in Java Web Applications: Concepts, Implementation, and Comparison

1. Difference Between Interceptor and Filter

Interceptors work on action requests (the external URL) while filters can intercept almost all requests, including static resources such as CSS and JS. Interceptors execute between the Servlet and the Controller, whereas filters run after the request enters the Tomcat container but before it reaches any Servlet.

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

On the response path, filters and interceptors are invoked after the Servlet has processed the request, before the response is sent back to the client.

2. Interceptor Code Implementation

2.1 Interceptor Class

The interceptor class must implement the HandlerInterceptor interface, which defines three methods:

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

@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
}

A typical preHandle implementation checks the session for a user object and redirects to the login page if the user is not authenticated:

@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;
}

Configuration in spring‑mvc.xml:

<!-- 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>

3. Filter Code Implementation

3.1 Filter Class

The filter class implements javax.servlet.Filter and must provide init, doFilter, and destroy methods:

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
    }
}

Configuration in web.xml:

<!-- Register custom filter -->
<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>

4. Summary of Differences

Scope: Interceptors can be used in web, application, and Swing layers; filters are limited to web applications.

Standard: Interceptors are Spring‑specific; filters are defined by the Servlet specification.

Invocation: Interceptors run only for action requests; filters can intercept any request, including static resources.

Access: Interceptors can access the Spring IoC container and beans; filters cannot.

Lifecycle: Interceptors may be invoked multiple times during an action’s lifecycle; filters are instantiated once at container startup.

5. Filter Fundamentals

5.1 What Is a Filter?

A filter, introduced in Servlet 2.3, implements javax.servlet.Filter and allows preprocessing of requests and postprocessing of responses before they reach the target servlet or after they leave it.

5.2 Filter API

The interface defines three methods: init(FilterConfig), doFilter(ServletRequest, ServletResponse, FilterChain), and destroy().

5.3 Filter Chain and Lifecycle

Multiple filters form a chain; each filter calls chain.doFilter(request, response) to pass control to the next filter. The order of execution is determined by the order of filter-mapping entries in web.xml. When the server starts, each filter’s init method is called once; on shutdown, destroy is invoked.

6. Interceptor Overview

Interceptors are part of the Spring container and support AOP concepts. They can execute code before and after controller methods, prevent method execution, and access the Spring IoC container to obtain beans.

7. Final Comparison Table

Interceptor: based on Java reflection, Spring‑managed, can access action context and IoC beans.

Filter: based on function callbacks, Servlet‑managed, cannot access Spring beans.

Interceptor works on action URLs; filter works on any URL pattern.

Interceptor can be invoked multiple times per request; filter is invoked once per request.

Both mechanisms are essential tools for implementing cross‑cutting concerns such as authentication, logging, and request preprocessing in Java web applications.

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.

aopWeb DevelopmentInterceptorServletSpring MVCfilter
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.