00:00

Filters vs Interceptors in Spring Boot

Last updated:

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. The DispatcherServlet calls interceptors around the handler, usually a controller method, after it has been selected.
Analogy: A filter is the security guard at the building entrance: everyone passes, whatever office they visit. An interceptor is the receptionist on a specific floor: they already know which person you came to see and can check whether that meeting needs an appointment.

2. Where They Run in a Request

Order of filters and interceptors in a Spring MVC requestA request enters the embedded server and passes through the servlet filter chain, including the Spring Security filters, before reaching the DispatcherServlet. The DispatcherServlet selects the handler, then calls each interceptor's preHandle, then the controller method. After the method returns, postHandle runs for view-based handlers, the response is written, and afterCompletion runs in reverse order. Control then returns back out through the filters. Servlet container (Tomcat) Filter chain security, logging, correlation ID DispatcherServlet Select handler preHandle interceptors in order Controller method postHandle (reverse order) afterCompletion (reverse order, also after exceptions)
Filters wrap the DispatcherServlet; interceptors wrap the controller method inside it.

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.

Filter skeleton
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

ApproachURL patternsOrderUse when
@Component on the filter classAll requests (/*)@Order or OrderedThe filter applies everywhere
FilterRegistrationBean in a @Bean methodAny patterns you setsetOrder(...)You need URL patterns, dispatcher types or explicit control
@WebFilter with @ServletComponentScanFrom the annotationNot reliably controllableReusing 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:

MethodCalledTypical 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 trueCleanup, 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:

WebConfig.java (registration)
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(tenantInterceptor)
            .addPathPatterns("/api/**")
            .excludePathPatterns("/api/docs/**");
}

5. Filter vs Interceptor: Key Differences

AspectServlet filterHandler interceptor
Defined byServlet specificationSpring MVC
RunsAround the whole servlet, for every matching URLAround the selected handler, inside DispatcherServlet
Sees static resources and error pagesYesOnly what goes through Spring MVC handlers
Knows the controller method and annotationsNoYes, through HandlerMethod
Can wrap or replace request and response objectsYesNo
Runs before Spring SecurityYes, if ordered before itNo, always after security filters
Exceptions handled by @RestControllerAdviceNoYes, for exceptions from preHandle
Registration@Component or FilterRegistrationBeanWebMvcConfigurer.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

RequestTimingFilter.java
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

PublicEndpoint.java
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 {
}
TenantInterceptor.java
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());
        }
    }
}
MissingTenantException.java
package com.javabytechie.shop.web;

public class MissingTenantException extends RuntimeException {
    public MissingTenantException() {
        super("The X-Tenant-Id header is required");
    }
}

6.3 Registration

WebConfig.java
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

ApiErrorHandler.java
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());
    }
}
CatalogController.java
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

Terminal
curl -s localhost:8080/api/products -H "X-Tenant-Id: acme"
curl -s localhost:8080/api/products
curl -s localhost:8080/api/public/status
Console
[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
Response without the header
{"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 @RestControllerAdvice never 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 inside DispatcherServlet, so @ExceptionHandler methods in a controller advice handle it, as in the example.
  • Returning false from preHandle: processing stops and nothing is written unless you write the response yourself. Throwing an exception is usually cleaner.
  • Exception in the controller: postHandle is skipped, afterCompletion runs, and the filter's code after chain.doFilter still runs (use finally to 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:

CatalogControllerTest.java
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

RequirementUseWhy
Correlation IDs, request logging, timingFilterCovers every request, including errors and static files
Wrapping the request or response (caching the body, compression)FilterOnly filters can replace the request and response objects
Authentication and authorizationSpring SecurityPurpose-built filter chain; do not rebuild it
Checks depending on controller annotationsInterceptorHas access to HandlerMethod
Adding common model attributes to viewsInterceptor (postHandle) or @ControllerAdviceRuns before view rendering
Business rules around service methodsNeither: AOPNot tied to HTTP; see AOP

10. Common Pitfalls

  • Registering a filter twice: annotating a filter with @Component and also wrapping a new instance in a FilterRegistrationBean creates two filters. Choose one.
  • Modifying the body in postHandle: for @RestController methods the body is already written when postHandle runs. Use a ResponseBodyAdvice or a filter instead.
  • Reading the request body in a filter: the input stream can be read only once. Use ContentCachingRequestWrapper if 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 OncePerRequestFilter instead of implementing Filter directly.
  • Set explicit orders relative to Spring Security's -100.
  • Throw exceptions from preHandle and 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