Filter vs. Interceptor in Spring: How to Choose and When to Use

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:

  1. Container-level execution: Filters wrap around the entire servlet pipeline, affecting all requests handled by the container.
  2. 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(...)
  3. 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 invoked
  • postHandle(...): After controller returns, before view is rendered
  • afterCompletion(...): After view rendering is complete

Characteristics:

  1. Operates within the Spring DispatcherServlet scope—it doesn’t apply to static content or servlet filters.
  2. Handler-level context: Can inspect handler objects and method annotations, giving finer control (e.g., customizing behavior per controller method)
  3. 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
FeatureServlet FilterSpring HandlerInterceptor
Execution ContextServlet container (e.g., Tomcat)Spring MVC DispatcherServlet and beyond
Runs onAll HTTP requestsOnly Spring-mapped handler requests
LifecycledoFilter(request, response, chain)preHandle, postHandle, afterCompletion
Access to Handler❌ No handler-specific knowledge✅ Can inspect handler method/annotations
Use CasesCORS, encoding, compression, request blockingHandler-specific auth checks, logging, metrics

💡 My Experience: When to Use Each

Spring Boot REST API

  • Filters: I configure a global CharacterEncodingFilter and CorsFilter 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 via WebMvcConfigurer.

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.

Kuni
Kuni

Hi, I’m a developer based in South Korea. With years of experience in the tech industry, I am passionate about creating meaningful solutions and continually learning in this ever-evolving field.

I believe in the importance of leading a healthy and balanced economic life, and I aim to share insights, ideas, and practical tips to help others achieve the same. Through this blog, I hope to connect with like-minded individuals, exchange valuable knowledge, and grow together.

Let’s explore, learn, and build a thriving life together!

Let me know if you'd like further adjustments! 😊