Spring’s HandlerInterceptor and Filter: Which One Fits Your Needs?

When I wrote the article Getting Started with Spring HandlerInterceptor, we received numerous questions asking about the difference between a HandlerInterceptor and a Filter, as well as where to use each of them. Because of this, I’ve decided to take a moment to write about it in a separate article and include it in my Spring MVC series. So, let’s get started!

HandlerIntercepter Interface

Handler interceptors, as discussed earlier, are part of Spring MVC. They provide a way to intercept incoming requests before they are handled by the controller. Interceptors are typically used for tasks such as logging, adding or modifying request attributes, and prohibiting the execution of the handler based on some authorization checks.

Here’s an example:

public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // pre-processing logic
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
         //  post-processing logic
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // after-completion processing logic
    }

}

To use this interceptor in your Spring MVC application, you can configure it in your configuration class or XML configuration:

@Configuration
@EnableWebMVC // to be used only if you're using an non-spring boot application 
public class AppConfig extends WebMvcConfigurerAdapter {
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor());
    }
}

Here, the addInterceptors() method is used to register theCustomInterceptor, ensuring that it intercepts all incoming requests and executes the necessary processing (you can apply the Custom interceptor only on some URL patterns using the addPathPatterns(“”) method).

Filter Interface

Filters, on the other hand, are part of the Java Servlet API and operate at a lower level compared to handler interceptors. They intercept requests before they reach the servlet (DispatcherServlet if using Spring MVC) and can also intercept responses before they are sent back to the client. Filters are typically used for tasks such as Global logging, encoding/decoding, Authentication, request/response modification, and caching.

Here’s an example of a filter:

@WebFilter(urlPatterns = "/*")
public class MyCustomFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       // Filter Initialized
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // Filtering Request
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        // Filter Destroyed
    }
}

To configure this filter in our Spring MVC application, we can use annotations like @WebFilter

Filters Versus Interceptors in Spring MVC

Before delving into the specific use cases of HandlerInterceptor and Filter, it’s essential to understand the interception flow within the Spring MVC request handling process. When a client sends an HTTP request to the Spring MVC application, the request first passes through any configured Filters. These Filters can perform tasks such as logging, encoding/decoding, or handling some security checks. After passing through the Filters, the request is then intercepted by HandlerInterceptor(s), if configured. HandlerInterceptor(s) provide a way to intercept requests before they are handled by the controller, allowing for tasks such as authorization, or adding/modifying some request attributes. Once the HandlerInterceptor(s) complete their processing, the request is finally dispatched to the appropriate controller handler method for further processing.

From the diagram, a clear distinction emerges between filters and interceptors, primarily in terms of execution timing. Filters operate even before the DispatcherServlet, making them ideal for tasks such as Authentication, Authorization, request modification, encoding, and more. Conversely, interceptors come into play just before the handler, making them suitable for pre/post-processing tasks like logging specific to the handler, and adding request attributes to the request which differs from the broader scope of functionalities achievable with filters.


Let’s delve into a practical scenario to grasp the distinctions between filters and interceptors, focusing on request modification. If you attempt to modify a request parameter directly using setParameter of the HttpServletRequest, you’ll find that such a method doesn’t exist. To achieve this in filters, you can create a wrapper using HttpServletRequestWrapperclass. By passing this wrapper instead of the original request to the rest of the filter chain, you can modify request parameters seamlessly. However, attempting the same modification using interceptors would result in an error, as interceptors operate at a different level and don’t provide direct access to request parameters for modification.

Another use case that requires filters, such as authentication, should be addressed at the initial stage of request processing. This preemptive handling avoids unnecessary execution of the DispatcherServlet and the subsequent handler mapping lookup, especially when the user’s authentication status is the primary concern. Utilizing a filter for this purpose would enhance efficiency and effectiveness.

HandlerInterceptor/Filter Use Cases

Filters, being part of the Java Servlet API, serve a broader range of use cases compared to HandlerInterceptor. Some common use cases for Filters in Spring MVC include:

  • Request and Response Manipulation: Modifying request parameters, headers, or response content before they reach the servlet or are sent back to the client.
  • Content Encoding and Decoding: Handling content encoding/decoding for requests and responses, such as compression or encryption.
  • Security Checks: Performing security checks, Authentication, Authorization, XSS prevention, or IP filtering.
  • Request Logging: Logging request details, including URI, headers, and payload, for monitoring or auditing purposes.
  • Performance Optimization: Implementing caching mechanisms, and response compression.

HandlerInterceptor in Spring MVC is used for various purposes to enhance the request-handling process. Some common use cases include:

  • Logging: Logging request details such as URI, method, headers, and client IP address for auditing or debugging purposes.
  • Adding/Modifying Request Attributes: Adding or modifying request attributes that can be used by the controller or view layer.
  • Preventing Requests: Stopping further processing of requests based on certain conditions, such as invalid input.

Conclusion

In conclusion, understanding the difference between HandlerInterceptor and Filter in Spring MVC is essential for designing robust and efficient web applications. While HandlerInterceptor is specific to Spring MVC and intercepts requests before they reach the controller for tasks like authentication and logging, Filters operate at a lower level within the servlet container, providing a broader range of capabilities such as request/response manipulation, security checks, and performance optimization. By leveraging the strengths of both HandlerInterceptor and Filter, developers can implement comprehensive request handling and processing mechanisms tailored to their application’s requirements, ensuring scalability, security, and maintainability.

Leave a Reply

Your email address will not be published. Required fields are marked *

Join the Tribe