Spring Interceptors vs Servlet Filters
Servlet Filters
The following image shows the typical layering of the handlers for a single HTTP request.
The client sends a request to the application, and the container creates a FilterChain
, which contains the Filter
instances and Servlet
that should process the HttpServletRequest
, based on the path of the request URI. In a Spring MVC application, the Servlet
is an instance of DispatcherServlet
. At most, one Servlet
can handle a single HttpServletRequest
and HttpServletResponse
. However, more than one Filter
can be used to:
- Prevent downstream
Filter
instances or theServlet
from being invoked. In this case, theFilter
typically writes theHttpServletResponse
. - Modify the
HttpServletRequest
orHttpServletResponse
used by the downstreamFilter
instances and theServlet
.
The power of the Filter
comes from the FilterChain
that is passed into it.
@Component
@Slf4j
public class MyCustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// initialized only once.
log.info(">>> int");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// This is invoked everytime the application receives a HttpServletRequest
log.info(">>> doFilter");
// do something before the rest of the application
// ...
// invoke the rest of the application
filterChain.doFilter(servletRequest, servletResponse);
// do something after the rest of the application
// ...
}
@Override
public void destroy() {
// destroyed when the application is shut down.
log.info(">>> destroy");
}
}
The order in which each Filter is invoked is extremely important.

Spring Interceptors

Differences


Spring Interceptors | Servlet Filters |
---|---|
Interface is HandlerInterceptor | Interface is jakarta.servlet.Filter |
HandlerIntercepter are part of Spring framework | Filter is related to the Servlet API (web servers) |
HandlerIntercepors intercepts requests between the DispatcherServlet and our Controllers. | Filters intercept requests before they reach the DispatcherServlet |
Spring Interceptors are similar to Servlet Filters but they act in Spring Context so are powerful to manage HTTP Request and Response but they can implement more sophisticated behaviour because can access all Spring context. | A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each HTTP response. This way is possible to manage HTTP incoming requests before they reach the resource, such as a JSP page, a servlet or a simple static page; in the same way, is possible to manage HTTP outbound response after resource execution. |
HandlerInterceptors should be registered in Spring application context. | Filters should be registered in ServletContext (web.xml or the new programmatic approach) |
Methods: afterCompletion(), postHandle(), preHandle() | Methods: init(), doFilter(), destroy() |
postHandle will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse since it’s already committed. | doFilter is much more versatile than the postHandle. You can change the request or response and pass it to the chain or even block the request processing. |
fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. | Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests. |
Use cases
- For incoming requests, we can use filters to manipulate and even block requests from reaching any servlet. Vice versa, we can also block responses from reaching the client.
- Spring security is a great example of using filters for authentication and authorization. To configure Spring Security, we simply need to add a single filter, the DelegatingFilterProxy. Spring Security can then intercept all incoming and outgoing traffic. This is why Spring Security can be used outside of Spring MVC.
- Spring Cloud Gateway uses filters.
Sample implementation
https://github.com/explorer436/programming-playground/tree/main/java-playground/spring-http-demo
Reading material
- https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html
- https://docs.oracle.com/javaee%2F6%2Fapi%2F%2F/javax/servlet/Filter.html