When building robust Spring Boot or Spring MVC applications, you’ll often need to execute reusable logic—like logging, authentication, or compression—before or after handling HTTP requests. But should you use a Servlet Filter or a Spring Interceptor? In my experience as a backend developer, understanding their differences is crucial for architecting clean and maintainable applications.
🔍 What Is a Servlet Filter?
A Filter is a Java class executed by the Servlet container (e.g., Tomcat) that can preprocess or postprocess every HTTP request and response—before it even reaches the servlet (DispatcherServlet
) or after the response leaves it.
Key characteristics:
- Container-level execution: Filters wrap around the entire servlet pipeline, affecting all requests handled by the container.
- Lifecycle method: Implemented via
doFilter(request, response, chain)
, which allows:- Inspection/modification of requests or responses
- Short-circuiting a request (e.g., blocking unauthorized access)
- Passing control further with
chain.doFilter(...
)
- Configuration order: Set in
web.xml
or via@WebFilter
, allowing explicit ordering by registration
Use cases:
- Cross-cutting concerns independent of the Spring context, such as global CORS handling, request encoding, or gzip compression.
🔍 What Is a Spring MVC Interceptor?
A HandlerInterceptor is a Spring-managed component that hooks into the controller execution lifecycle, allowing logic before the handler runs, after it executes, and after completion of view rendering
Controller-level lifecycle methods:
preHandle(...)
: Before the controller method is invokedpostHandle(...)
: After controller returns, before view is renderedafterCompletion(...)
: After view rendering is complete
Characteristics:
- Operates within the Spring DispatcherServlet scope—it doesn’t apply to static content or servlet filters.
- Handler-level context: Can inspect handler objects and method annotations, giving finer control (e.g., customizing behavior per controller method)
- Configuration order matters: Interceptors are registered in
WebMvcConfigurer#addInterceptors
, and execution follows registration order
Use cases:
- Handler-specific logic, such as per-endpoint authentication, permission checking, request logging with handler info, or adding data to the model.
🆚 Filter vs Interceptor: Side-by-Side
Feature | Servlet Filter | Spring HandlerInterceptor |
---|---|---|
Execution Context | Servlet container (e.g., Tomcat) | Spring MVC DispatcherServlet and beyond |
Runs on | All HTTP requests | Only Spring-mapped handler requests |
Lifecycle | doFilter(request, response, chain) | preHandle , postHandle , afterCompletion |
Access to Handler | ❌ No handler-specific knowledge | ✅ Can inspect handler method/annotations |
Use Cases | CORS, encoding, compression, request blocking | Handler-specific auth checks, logging, metrics |
💡 My Experience: When to Use Each
Spring Boot REST API
- Filters: I configure a global
CharacterEncodingFilter
andCorsFilter
as Filters since they apply to all incoming HTTP traffic. - Interceptors: For API-specific logic—such as validating JWT tokens or logging user and endpoint details—I prefer Interceptors. They give me access to handler method metadata for role-based access decisions.
Complex Projects
- I use Filters for cross-cutting concerns that should run before any request reaches Spring.
- I use Interceptors for request-specific behaviors—especially when I need context about which controller or method is being executed.
✅ Best Practices
- Use Filters for universal preprocessing tasks (request encoding, CORS, compression).
- Use Interceptors for handler-level concerns (authentication, authorization, metrics with handler context).
- Layer your filters and interceptors wisely:
- Filters first → Interceptors → Controllers → Filters on response exit.
- Register Filters via
@WebFilter
/FilterRegistrationBean
, and Interceptors viaWebMvcConfigurer
.
In most modern Spring projects, both tools work together—Filters set up environments or block requests instantly, and Interceptors add handler-scoped logic and enhance observability.
🧠 Final Thoughts
Understanding the filter vs interceptor distinction is key to designing clean, maintainable web applications. Filters handle container-level tasks, while Interceptors give you Spring MVC request context and handler-specific insights.
By using each tool for its intended scope, you build clearer pipelines, avoid misuse, and create robust, well-structured applications that respond appropriately—whether you’re setting global policies or adding endpoint-level controls.