Difference Between Interceptor and Filter in Java Web Applications and Their Implementation

This article explains the conceptual differences between Spring MVC interceptors and Servlet filters, shows how to implement each with Java code, details their configuration in Spring and web.xml, and summarizes when to use one over the other in backend development.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Difference Between Interceptor and Filter in Java Web Applications and Their Implementation

1. Difference between Interceptor and Filter

Interceptors (Interceptor) only work on action requests (i.e., controller URLs), while Filters can affect almost all requests, including static resources such as CSS and JS files.

Interceptors are executed between the Servlet and the Spring MVC 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

When the response is returned, the order is the same: after the Servlet finishes, the Interceptor runs before the response is sent to the client.

2. Interceptor implementation

First, create a class that implements 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 whether a user session exists and redirects to the login page if not:

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

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

3. Filter implementation

Create a class that implements javax.servlet.Filter and override its three lifecycle 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");
        }
        filterChain.doFilter(request, response);
    }

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

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

4. Summary of differences

Interceptors work within the Spring container and can be used in web, application, or Swing layers; Filters are defined by the Servlet specification and only apply to web applications.

Interceptors rely on Java reflection and can access the Spring IoC container; Filters use function callbacks and cannot access Spring beans directly.

Interceptors are invoked for each action request, while Filters can intercept virtually all requests, including static resources.

Interceptors can be called multiple times during an action’s lifecycle; Filters are instantiated once at container startup.

Both can be used for cross‑cutting concerns such as authentication, logging, and request preprocessing.

In essence, interceptors embody AOP concepts within Spring, whereas filters provide a lower‑level, servlet‑container‑based mechanism for request preprocessing.

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.

InterceptorSpring MVCfilter
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.