What is the difference between HandlerInterceptor and Filter?
In Spring Boot applications, both `HandlerInterceptor` and `Filter` are mechanisms to intercept requests and responses, allowing for common processing logic to be applied across multiple handlers or servlets. While they serve similar high-level purposes, they operate at different layers of the application stack, offering distinct capabilities and use cases.
Key Differences
The fundamental difference lies in their scope and the layer at which they operate. Filters are part of the Servlet specification and operate at the web container level, before any Spring MVC components are involved. HandlerInterceptors, on the other hand, are a feature of Spring MVC and operate within the Spring DispatcherServlet's processing lifecycle, providing more granular control related to Spring's handler execution.
| Feature | Filter | HandlerInterceptor |
|---|---|---|
| API | Servlet API (javax.servlet.Filter) | Spring MVC API (org.springframework.web.servlet.HandlerInterceptor) |
| Scope/Layer | Servlet container level, before DispatcherServlet | Spring MVC layer, within DispatcherServlet |
| Access to Spring Context | Limited direct access (can be injected via Spring proxy/wrapper) | Full access to Spring beans and context |
| Access to Handler (Controller) | No direct access to the specific handler/controller method | Direct access to the handler (Controller method) that will be invoked |
| Methods | doFilter(ServletRequest, ServletResponse, FilterChain) | preHandle(), postHandle(), afterCompletion() |
| Lifecycle | Initialized once by servlet container | Initialized once by Spring container |
| Use Cases | Request/response encoding, authentication (basic), logging, request modification, XSS/CSRF protection. | Logging (method specific), authentication (Spring Security integration), authorization, data binding, view preparation, monitoring handler execution time. |
| Exception Handling | Can handle exceptions before/after the servlet chain | Can handle exceptions during/after handler execution, and before view rendering. |
| Order of Execution | Configured in web.xml or via @Order for Servlet filters | Configured via WebMvcConfigurer.addInterceptors and ordered by registration sequence or @Order. |
HandlerInterceptor
A HandlerInterceptor is a Spring MVC-specific component that allows you to intercept requests *after* they have been mapped to a handler (a controller method) but *before* the handler actually executes, and also *after* the handler has executed, and *after* the complete request has finished (including view rendering). It is part of the Spring MVC request processing pipeline and provides more fine-grained control over the Spring application's lifecycle.
- Operates within the Spring
DispatcherServlet. - Has access to the
Handler(the specific controller method) that will be invoked. - Can access and modify the
ModelAndViewbefore the view is rendered. - Provides three distinct callback methods:
- -
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler): Called before the handler is executed. Returnstrueto proceed,falseto stop further processing. - -
postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView): Called after the handler is executed, but before the view is rendered. Can modify theModelAndView. - -
afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex): Called after the complete request has finished and the view has been rendered. Useful for resource cleanup, even if an exception occurred.
Filter
A Filter is a standard component defined by the Java Servlet API. It operates at the web container level, meaning it intercepts requests *before* they even reach the Spring DispatcherServlet. Filters are generic and are not tied to any specific framework like Spring MVC. They are ideal for operations that are common to all incoming requests, regardless of which servlet or handler will eventually process them.
- Operates at the Servlet container level, before the
DispatcherServlet. - Does not have direct access to the specific handler/controller method that Spring MVC will invoke.
- Can modify the request and response objects before they are passed down the chain.
- Provides a single
doFiltermethod: - -
doFilter(ServletRequest request, ServletResponse response, FilterChain chain): Contains the logic to perform before and after passing the request to the next element in the chain (chain.doFilter(...)).
When to use which?
- Spring MVC specific logic: When your interception logic requires access to Spring MVC components like the handler method,
ModelAndView, or Spring's application context. - Fine-grained control post-handler execution: If you need to manipulate the
ModelAndViewor perform actions *after* a controller method has processed the request but *before* the view is rendered. - Logging and monitoring handler execution: To track the execution time of specific controller methods or log details tied to specific handlers.
- Authorization and authentication (Spring Security): While Filters can handle basic authentication, Interceptors are often integrated with Spring Security for more sophisticated authorization logic tied to specific endpoints/handlers.
- Data binding or validation related to specific handlers.
- Global, generic operations: When the logic needs to apply to *all* incoming requests, regardless of whether they are handled by Spring MVC or other servlets (e.g., static resources).
- Request/response modification: For operations like character encoding, header manipulation, or compression that need to happen at the earliest stage.
- Security aspects independent of Spring MVC: For basic authentication, session management, XSS protection, or CSRF token handling that can be applied universally.
- Logging general request information: To log all incoming request URLs, IP addresses, etc., before any framework-specific processing.
In summary, choose Filter for broad, generic web concerns operating at the Servlet container level, and HandlerInterceptor for Spring MVC-specific concerns that require deeper integration with Spring's request processing lifecycle and handler details.