Filters vs Interceptors in Spring Boot
Filters vs interceptors in Spring Boot is a common design question: both let you run code before and after every HTTP request, for example to log timings, check an API key or set a correlation ID. The difference is where they sit. A servlet filter wraps the whole request at the servlet container level, before Spring MVC is involved. A handler interceptor runs inside Spring MVC, after it has chosen which controller method will handle the request, so it knows the target method and its annotations.
This tutorial shows how each works, in what order they run, how to register and order them, how they behave when something fails, and how to choose between them. A complete example combines a timing filter with a tenant-checking interceptor and tests both.
1. What Are Filters and Interceptors?
- A filter (
jakarta.servlet.Filter) is part of the Servlet specification. The servlet container, such as Tomcat, calls a chain of filters for every request that matches their URL patterns, and the last link of the chain is a servlet. Filters can change or replace the request and response, or stop the request entirely. - An interceptor (
org.springframework.web.servlet.HandlerInterceptor) is a Spring MVC concept. TheDispatcherServletcalls interceptors around the handler, usually a controller method, after it has been selected.
2. Where They Run in a Request
The full path for one request is therefore: filter 1 → filter 2 → … → DispatcherServlet → interceptor preHandle calls → controller → postHandle calls (reverse order) → response rendering → afterCompletion calls (reverse order) → back out through the filters. The Spring Boot architecture page shows the same flow from the layer perspective.
3. Servlet Filters in Spring Boot
3.1 Writing a Filter with OncePerRequestFilter
Spring's OncePerRequestFilter guarantees one execution per request, even when a request is forwarded or dispatched again for error handling. You implement doFilterInternal and call chain.doFilter to continue; not calling it stops the request.
public class ExampleFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
// before the rest of the chain
chain.doFilter(request, response);
// after the response has been produced
}
}
3.2 Registering a Filter
| Approach | URL patterns | Order | Use when |
|---|---|---|---|
@Component on the filter class | All requests (/*) | @Order or Ordered | The filter applies everywhere |
FilterRegistrationBean in a @Bean method | Any patterns you set | setOrder(...) | You need URL patterns, dispatcher types or explicit control |
@WebFilter with @ServletComponentScan | From the annotation | Not reliably controllable | Reusing existing servlet-standard filters |
Spring Security's filter chain is registered as one filter with order -100 by default. Filters with a lower order value run before security; higher values run after it, when the user is already authenticated. For filters inside the security chain itself, see custom filters in Spring Security.
4. Handler Interceptors in Spring MVC
HandlerInterceptor has three default methods:
| Method | Called | Typical use |
|---|---|---|
preHandle(request, response, handler) | Before the controller. Returning false stops processing. | Checks based on the target method, such as required headers or permissions |
postHandle(request, response, handler, modelAndView) | After the controller returns, before view rendering. Not called if the controller throws. | Adding model attributes for server-rendered views |
afterCompletion(request, response, handler, ex) | After the response is complete, also after exceptions, for every interceptor whose preHandle returned true | Cleanup, metrics, logging the outcome |
The handler argument is usually a HandlerMethod, which gives access to the controller class, the method and its annotations. That is the interceptor's main advantage over a filter. Register interceptors through a WebMvcConfigurer, optionally limited by path patterns:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tenantInterceptor)
.addPathPatterns("/api/**")
.excludePathPatterns("/api/docs/**");
}
5. Filter vs Interceptor: Key Differences
| Aspect | Servlet filter | Handler interceptor |
|---|---|---|
| Defined by | Servlet specification | Spring MVC |
| Runs | Around the whole servlet, for every matching URL | Around the selected handler, inside DispatcherServlet |
| Sees static resources and error pages | Yes | Only what goes through Spring MVC handlers |
| Knows the controller method and annotations | No | Yes, through HandlerMethod |
| Can wrap or replace request and response objects | Yes | No |
| Runs before Spring Security | Yes, if ordered before it | No, always after security filters |
Exceptions handled by @RestControllerAdvice | No | Yes, for exceptions from preHandle |
| Registration | @Component or FilterRegistrationBean | WebMvcConfigurer.addInterceptors |
6. A Complete Example: Request Timing and Tenant Checks
A multi-tenant shop API needs two things: every /api request is timed and logged, and every endpoint except those marked public requires an X-Tenant-Id header. Timing applies to everything and needs no Spring MVC details, so it is a filter. The tenant rule depends on an annotation on the controller method, so it is an interceptor.
6.1 The Timing Filter
package com.javabytechie.shop.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;
public class RequestTimingFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(RequestTimingFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
long start = System.nanoTime();
log.info("[filter] before {} {}", request.getMethod(), request.getRequestURI());
try {
chain.doFilter(request, response);
} finally {
long millis = (System.nanoTime() - start) / 1_000_000;
log.info("[filter] after {} {} -> {} in {} ms",
request.getMethod(), request.getRequestURI(), response.getStatus(), millis);
}
}
}
6.2 The Public Endpoint Annotation and Tenant Interceptor
package com.javabytechie.shop.web;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PublicEndpoint {
}
package com.javabytechie.shop.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class TenantInterceptor implements HandlerInterceptor {
static final String TENANT_HEADER = "X-Tenant-Id";
static final String TENANT_ATTRIBUTE = "tenantId";
private static final Logger log = LoggerFactory.getLogger(TenantInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!(handler instanceof HandlerMethod method) || method.hasMethodAnnotation(PublicEndpoint.class)) {
return true; // static resources and public endpoints need no tenant
}
String tenant = request.getHeader(TENANT_HEADER);
if (tenant == null || tenant.isBlank()) {
throw new MissingTenantException();
}
request.setAttribute(TENANT_ATTRIBUTE, tenant);
log.info("[interceptor] preHandle {} for tenant {}", method.getMethod().getName(), tenant);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
if (handler instanceof HandlerMethod method) {
log.info("[interceptor] afterCompletion {} (exception: {})",
method.getMethod().getName(), ex == null ? "none" : ex.getClass().getSimpleName());
}
}
}
package com.javabytechie.shop.web;
public class MissingTenantException extends RuntimeException {
public MissingTenantException() {
super("The X-Tenant-Id header is required");
}
}
6.3 Registration
package com.javabytechie.shop.web;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final TenantInterceptor tenantInterceptor;
public WebConfig(TenantInterceptor tenantInterceptor) {
this.tenantInterceptor = tenantInterceptor;
}
@Bean
FilterRegistrationBean<RequestTimingFilter> requestTimingFilter() {
FilterRegistrationBean<RequestTimingFilter> registration = new FilterRegistrationBean<>(new RequestTimingFilter());
registration.addUrlPatterns("/api/*");
registration.setOrder(-200); // before Spring Security (-100), so timing includes it
return registration;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tenantInterceptor).addPathPatterns("/api/**");
}
}
6.4 Error Handling and the Controller
package com.javabytechie.shop.web;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
class ApiErrorHandler {
@ExceptionHandler(MissingTenantException.class)
ProblemDetail missingTenant(MissingTenantException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage());
}
}
package com.javabytechie.shop.web;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class CatalogController {
private static final Logger log = LoggerFactory.getLogger(CatalogController.class);
@GetMapping("/products")
public List<String> products(@RequestAttribute(TenantInterceptor.TENANT_ATTRIBUTE) String tenantId) {
log.info("[controller] listing products for {}", tenantId);
return List.of(tenantId + ":KB-100", tenantId + ":MS-200");
}
@PublicEndpoint
@GetMapping("/public/status")
public String status() {
return "UP";
}
}
6.5 Run It
curl -s localhost:8080/api/products -H "X-Tenant-Id: acme"
curl -s localhost:8080/api/products
curl -s localhost:8080/api/public/status
[filter] before GET /api/products
[interceptor] preHandle products for tenant acme
[controller] listing products for acme
[interceptor] afterCompletion products (exception: none)
[filter] after GET /api/products -> 200 in 6 ms
[filter] before GET /api/products
[filter] after GET /api/products -> 400 in 3 ms
[filter] before GET /api/public/status
[filter] after GET /api/public/status -> 200 in 1 ms
{"type":"about:blank","title":"Bad Request","status":400,"detail":"The X-Tenant-Id header is required","instance":"/api/products"}
The filter wraps everything, including the failed request; the interceptor runs only around the handler, and because it threw in preHandle, its own afterCompletion is not called. The controller advice turned the exception into a ProblemDetail. Timings will differ on your machine.
7. How Errors Behave in Filters and Interceptors
- Exception in a filter: it happens outside Spring MVC, so
@RestControllerAdvicenever sees it. The container forwards to Spring Boot's error handling (/error), which returns a generic error response. Either write the error response in the filter yourself or avoid throwing there. - Exception in
preHandle: it happens insideDispatcherServlet, so@ExceptionHandlermethods in a controller advice handle it, as in the example. - Returning
falsefrompreHandle: processing stops and nothing is written unless you write the response yourself. Throwing an exception is usually cleaner. - Exception in the controller:
postHandleis skipped,afterCompletionruns, and the filter's code afterchain.doFilterstill runs (usefinallyto be safe).
See exception handling in Spring Boot for the error handling chain.
8. Testing Filters and Interceptors
@WebMvcTest includes Filter and FilterRegistrationBean beans, WebMvcConfigurer classes and HandlerInterceptor beans, so the whole chain runs in a fast slice test:
package com.javabytechie.shop.web;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@WebMvcTest(CatalogController.class)
class CatalogControllerTest {
@Autowired
MockMvcTester mvc;
@Test
void rejectsRequestsWithoutTenant() {
assertThat(mvc.get().uri("/api/products"))
.hasStatus(HttpStatus.BAD_REQUEST)
.bodyJson().extractingPath("$.detail").isEqualTo("The X-Tenant-Id header is required");
}
@Test
void passesTheTenantToTheController() {
assertThat(mvc.get().uri("/api/products").header("X-Tenant-Id", "acme"))
.hasStatus(HttpStatus.OK)
.bodyJson().extractingPath("$[0]").isEqualTo("acme:KB-100");
}
@Test
void publicEndpointsNeedNoTenant() {
assertThat(mvc.get().uri("/api/public/status")).hasStatus(HttpStatus.OK);
}
}
9. When to Use Which
| Requirement | Use | Why |
|---|---|---|
| Correlation IDs, request logging, timing | Filter | Covers every request, including errors and static files |
| Wrapping the request or response (caching the body, compression) | Filter | Only filters can replace the request and response objects |
| Authentication and authorization | Spring Security | Purpose-built filter chain; do not rebuild it |
| Checks depending on controller annotations | Interceptor | Has access to HandlerMethod |
| Adding common model attributes to views | Interceptor (postHandle) or @ControllerAdvice | Runs before view rendering |
| Business rules around service methods | Neither: AOP | Not tied to HTTP; see AOP |
10. Common Pitfalls
- Registering a filter twice: annotating a filter with
@Componentand also wrapping a new instance in aFilterRegistrationBeancreates two filters. Choose one. - Modifying the body in
postHandle: for@RestControllermethods the body is already written whenpostHandleruns. Use aResponseBodyAdviceor a filter instead. - Reading the request body in a filter: the input stream can be read only once. Use
ContentCachingRequestWrapperif you must log it. - Interceptor beans with heavy dependencies: they are created during Spring MVC setup; keep them light.
- Forgetting
finally: cleanup such as removing MDC values must run even when the request fails.
11. Best Practices
- Use filters for cross-cutting HTTP concerns that apply to every request.
- Use interceptors when the decision depends on the handler, such as a method annotation.
- Extend
OncePerRequestFilterinstead of implementingFilterdirectly. - Set explicit orders relative to Spring Security's
-100. - Throw exceptions from
preHandleand map them in one controller advice. - Keep both thin; move business logic into services.
- Test the chain with
@WebMvcTest, including the failure paths.
12. Summary
Filters vs interceptors in Spring Boot comes down to position. Servlet filters wrap the whole request in the servlet container, see every URL, can replace the request and response and can run before Spring Security, but know nothing about controllers and bypass controller advice. Handler interceptors run inside DispatcherServlet around the chosen handler, can read its annotations through HandlerMethod, and their preHandle exceptions reach @RestControllerAdvice. Use a filter for logging, timing and correlation IDs, an interceptor for handler-specific checks, Spring Security for authentication, and AOP for business rules.
13. References
Filters vs Interceptors in Spring Boot Interview Questions and Answers
Common interview questions on Filters vs Interceptors in Spring Boot, from basic to scenario-based, with short answers you can explain in your own words.
Q. What is the difference between a filter and an interceptor in Spring Boot?
Answer: A filter is a Servlet API component that the container runs around the whole request, before DispatcherServlet; it can wrap the request and response but does not know the controller. An interceptor is a Spring MVC component that runs inside DispatcherServlet around the selected handler, so it can inspect the controller method and its annotations. Exceptions from interceptors reach controller advice; exceptions from filters do not.
Q. What are preHandle, postHandle and afterCompletion, and when is each skipped?
Answer: preHandle runs before the handler and can stop processing by returning false. postHandle runs after a successful handler call, before view rendering, and is skipped when the handler throws. afterCompletion runs after the request completes, including after exceptions, but only for interceptors whose preHandle returned true; postHandle and afterCompletion run in reverse order.
Q. How do you apply a filter only to certain URLs and control its order?
Answer: Declare a FilterRegistrationBean in a @Bean method, set its URL patterns with addUrlPatterns and its position with setOrder, and do not also annotate the filter with @Component. A filter registered just as a @Component applies to all URLs and can be ordered with @Order. Order values below Spring Security's default of -100 run before security.
Q. Why is an exception thrown in a filter not handled by @RestControllerAdvice?
Answer: Controller advice is applied by DispatcherServlet's exception resolvers, and a filter runs before or around DispatcherServlet, outside that mechanism. The exception goes to the servlet container, which forwards to Spring Boot's /error handling. Write the error response directly in the filter, or delegate to a HandlerExceptionResolver bean, if you need a custom format.
Q. Why does changing the response body in postHandle not work for @RestController methods?
Answer: For @ResponseBody handlers the message converter writes the body as part of handling the return value, before postHandle is called, so the response is usually already committed. postHandle is mainly useful for view-based controllers. To modify REST response bodies use a ResponseBodyAdvice, and for headers or wrapping use a filter.
Q. You need to log the request body of failed API calls. Where would you implement this?
Answer: In a filter that wraps the request in ContentCachingRequestWrapper, calls the chain, and afterwards logs the cached body when the response status is 4xx or 5xx. The input stream can only be read once, so wrapping before the controller is essential. Limit the cached size, mask sensitive fields, and avoid logging bodies of authentication or payment endpoints.