Spring Boot filters: the chain around every request

A servlet filter runs before Spring MVC sees a request and after the response is built, which makes it the place for security, request ids, logging and proxy handling. This page shows how Spring Boot registers and orders filters, then runs URL-specific registration, body wrappers, the built-in ETag and forwarded-header filters, and the traps that skip code or empty responses.

Contents

What a servlet filter does

A filter is code that runs around every HTTP request before it reaches Spring MVC, and around the response on its way back. It belongs to the Servlet API, not to Spring: the interface is jakarta.servlet.Filter, with one main method, doFilter(request, response, chain).

Filters form a chain. The servlet container calls the first filter, which can do some work and then call chain.doFilter(request, response) to pass the request on. The last link in the chain is the servlet itself, which in a Spring Boot application is the DispatcherServlet. When chain.doFilter returns, the response has been produced, and the filter can run code afterwards. A filter can also decide not to call the chain, and answer the request itself.

That shape makes filters the right place for concerns that apply to every request, independent of which controller handles it:

  • Security: authentication and authorization; Spring Security is itself one filter that contains its own chain of filters.
  • Request metadata: request ids, logging context, character encoding.
  • Request and response rewriting: compression, caching headers, proxy headers.
  • Cross-cutting limits: rate limits and request size checks.

Because a filter runs before Spring MVC chooses a controller, it knows only the raw request: the URL, the headers and the body. It does not know which controller method will run. When you need that, use a handler interceptor instead.

Ways to write and register a filter
WayApplies toBest for
Filter bean (@Component or @Bean)All URLs, REQUEST dispatch onlySimple filters for the whole application
OncePerRequestFilter subclassSame, but at most once per requestMost filters written for Spring applications
FilterRegistrationBeanChosen URL patterns, order, dispatcher typesFilters that apply to part of the application
@WebFilter with @ServletComponentScanWhat the annotation saysCode shared with plain servlet applications
Spring Security's SecurityFilterChainPaths matched by its rulesAnything to do with authentication

The programs on this page use Spring Boot 4.1 with Spring Framework 7.0, Tomcat 11 and spring-boot-starter-webmvc. Each starts on a random port, sends requests to itself and prints what each filter saw.

How Spring Boot registers and orders filters

To see the chain, this program registers three filters that print when a request enters and leaves them: a plain Filter, a OncePerRequestFilter with a finally block, and one registered by hand for the error dispatch too. It also prints the filters Spring Boot registered, then sends one request that succeeds and one whose controller throws:

Java
package demo.order;

import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializerBeans;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.OncePerRequestFilter;

@SpringBootApplication
public class FilterChainOrder {

    // A plain servlet filter: Spring Boot registers every Filter bean for /*
    @Component
    @Order(1)
    static class PlainFilter implements Filter {
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            System.out.println("  PlainFilter  in : " + request.getDispatcherType()
                    + " " + request.getRequestURI());
            chain.doFilter(req, res);
            System.out.println("  PlainFilter  out: status "
                    + ((HttpServletResponse) res).getStatus());
        }
    }

    // OncePerRequestFilter skips the ERROR and ASYNC dispatches by default
    @Component
    @Order(2)
    static class OnceFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {
            System.out.println("  OnceFilter   in : " + request.getDispatcherType()
                    + " " + request.getRequestURI());
            try {
                chain.doFilter(request, response);
            } finally {
                System.out.println("  OnceFilter   out: status " + response.getStatus()
                        + " (finally)");
            }
        }
    }

    // Registered by hand, to also run on the ERROR dispatch to /error
    @Bean
    FilterRegistrationBean<Filter> errorAwareFilter() {
        Filter filter = (req, res, chain) -> {
            HttpServletRequest request = (HttpServletRequest) req;
            System.out.println("  ErrorAware   in : " + request.getDispatcherType()
                    + " " + request.getRequestURI());
            chain.doFilter(req, res);
        };
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(filter);
        registration.setName("errorAwareFilter");
        registration.setOrder(3);
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ERROR);
        return registration;
    }

    @RestController
    static class HelloController {
        @GetMapping("/hello")
        public String hello() {
            System.out.println("  controller runs");
            return "hi";
        }

        @GetMapping("/boom")
        public String boom() {
            throw new IllegalStateException("boom");
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(FilterChainOrder.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .run(args)) {
            System.out.println("Filters Spring Boot registers, in order:");
            new ServletContextInitializerBeans(context.getBeanFactory()).stream()
                    .filter(FilterRegistrationBean.class::isInstance)
                    .map(FilterRegistrationBean.class::cast)
                    .forEach(r -> System.out.printf("  %-28s order %d%n",
                            r.getFilterName(), r.getOrder()));

            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            for (String path : new String[] {"/hello", "/boom"}) {
                System.out.println("GET " + path);
                int status = http.send(HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + path)).build(),
                        BodyHandlers.discarding()).statusCode();
                System.out.println("  client receives " + status);
            }
        }
    }
}
Output
Filters Spring Boot registers, in order:
  characterEncodingFilter      order -2147483648
  formContentFilter            order -9900
  requestContextFilter         order -105
  filterChainOrder.PlainFilter order 1
  filterChainOrder.OnceFilter  order 2
  errorAwareFilter             order 3
GET /hello
  PlainFilter  in : REQUEST /hello
  OnceFilter   in : REQUEST /hello
  ErrorAware   in : REQUEST /hello
  controller runs
  OnceFilter   out: status 200 (finally)
  PlainFilter  out: status 200
  client receives 200
GET /boom
  PlainFilter  in : REQUEST /boom
  OnceFilter   in : REQUEST /boom
  ErrorAware   in : REQUEST /boom
  OnceFilter   out: status 200 (finally)
  ErrorAware   in : ERROR /error
  client receives 500
  • Spring Boot found every Filter bean and registered it with Tomcat for /*, sorted by @Order. It also added three filters of its own: characterEncodingFilter first of all, so that request parameters are decoded as UTF-8, then formContentFilter and requestContextFilter.
  • For /hello, the filters were entered in order 1, 2, 3, and left in reverse order after the controller ran. The chain nests like method calls: the first filter in is the last one out.
  • For /boom, the controller threw, and the exception travelled back up through chain.doFilter. PlainFilter never printed its out line, because its code after the call was skipped. Only OnceFilter, which used finally, ran its closing code. Code that must always run, such as clearing a ThreadLocal or recording a metric, belongs in finally.
  • In that finally block the status was still 200, although the client received 500. The error status is set later, by Tomcat, when it handles the exception.
  • Tomcat then forwarded the request to /error, as a second pass through the chain with the dispatcher type ERROR. Only errorAwareFilter ran again, because it was registered with DispatcherType.ERROR. Spring Boot registers ordinary Filter beans for REQUEST only.

The order numbers matter when your filter must run before or after another one. Lower numbers run first. Spring Security's filter is registered with order -100 by default (spring.security.filter.order), so a filter with order 1 runs after authentication, and one that must run before it needs an order below -100.

Choosing where a filter applies with FilterRegistrationBean

An API key check should protect the API without blocking the home page or a public status endpoint. Registering the filter with a FilterRegistrationBean limits it to /api/*, and shouldNotFilter makes one more exception inside that pattern:

Java
package demo.registration;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.OncePerRequestFilter;

@SpringBootApplication
public class FilterRegistration {

    // Not a @Component: registered below, only for /api/*
    static class ApiKeyFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {
            if (!"secret-1".equals(request.getHeader("X-Api-Key"))) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.getWriter().write("{\"error\":\"missing or wrong API key\"}");
                return;                              // the chain stops here
            }
            chain.doFilter(request, response);
        }

        @Override
        protected boolean shouldNotFilter(HttpServletRequest request) {
            return request.getRequestURI().startsWith("/api/public/");
        }
    }

    @Bean
    FilterRegistrationBean<ApiKeyFilter> apiKeyFilter() {
        FilterRegistrationBean<ApiKeyFilter> registration =
                new FilterRegistrationBean<>(new ApiKeyFilter());
        registration.addUrlPatterns("/api/*");
        registration.setOrder(10);
        return registration;
    }

    @RestController
    static class Endpoints {
        @GetMapping("/api/orders")
        public String orders() {
            return "orders for a known client";
        }

        @GetMapping("/api/public/status")
        public String status() {
            return "up";
        }

        @GetMapping("/home")
        public String home() {
            return "home page";
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(FilterRegistration.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            String[][] calls = {
                {"/api/orders", null}, {"/api/orders", "wrong"}, {"/api/orders", "secret-1"},
                {"/api/public/status", null}, {"/home", null}};
            for (String[] call : calls) {
                HttpRequest.Builder request = HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + call[0]));
                if (call[1] != null) {
                    request.header("X-Api-Key", call[1]);
                }
                HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
                System.out.printf("GET %-20s key=%-9s -> %d %s%n",
                        call[0], call[1], r.statusCode(), r.body());
            }
        }
    }
}
Output
GET /api/orders          key=null      -> 401 {"error":"missing or wrong API key"}
GET /api/orders          key=wrong     -> 401 {"error":"missing or wrong API key"}
GET /api/orders          key=secret-1  -> 200 orders for a known client
GET /api/public/status   key=null      -> 200 up
GET /home                key=null      -> 200 home page
  • Without a key and with the wrong key, the filter answered 401 with a JSON body and returned without calling chain.doFilter. The controller never ran, and nothing later in the chain saw the request.
  • With the right key, the filter passed the request on and the controller answered 200.
  • /api/public/status matched the URL pattern, but shouldNotFilter returned true, so the filter skipped it. This hook of OncePerRequestFilter is clearer than an if at the top of doFilterInternal.
  • /home is outside /api/*, so Tomcat never called the filter at all.

The filter class has no @Component, and that matters. In a separate test, a filter class with @Component and also a FilterRegistrationBean that created a second instance ran twice for /api/x: once as a bean registered for /*, and once through the registration. Create the filter in one place only. Servlet URL patterns are simple: /api/* for a prefix, *.json for an extension, or an exact path; Spring's {id} patterns do not work here.

A FilterRegistrationBean with setEnabled(false) is also how you stop Spring Boot from registering a filter bean with the servlet container. That is needed for a filter that is only meant to be added to Spring Security's chain, so that it does not also run on its own.

Reading and changing the body with wrappers

A filter cannot simply read the request body: the body is a stream, and once read, the controller would get nothing. Spring provides wrappers that cache the body while the rest of the chain reads it. This program logs both bodies and adds a request id. It sends the same request twice, the second time without the one line every response-caching filter needs:

Java
package demo.wrappers;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

@SpringBootApplication
public class BodyWrappers {

    static boolean copyBody = true;   // the program turns this off to show the trap

    @Component
    @Order(1)
    static class RequestIdFilter extends OncePerRequestFilter {
        private final AtomicInteger next = new AtomicInteger(100);

        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {
            String id = "req-" + next.incrementAndGet();
            request.setAttribute("requestId", id);      // for code later in the chain
            response.setHeader("X-Request-Id", id);     // for the client
            chain.doFilter(request, response);
        }
    }

    @Component
    @Order(2)
    static class BodyLoggingFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {
            var req = new ContentCachingRequestWrapper(request, 1024);
            var res = new ContentCachingResponseWrapper(response);
            chain.doFilter(req, res);
            System.out.println("  logged request : "
                    + new String(req.getContentAsByteArray(), StandardCharsets.UTF_8));
            System.out.println("  logged response: " + res.getStatus() + " "
                    + new String(res.getContentAsByteArray(), StandardCharsets.UTF_8));
            if (copyBody) {
                res.copyBodyToResponse();   // without this the client gets no body
            }
        }
    }

    public record Greeting(String name) {}

    @RestController
    static class GreetingController {
        @PostMapping("/greet")
        public String greet(@RequestBody Greeting greeting, HttpServletRequest request) {
            return "hello " + greeting.name() + " (" + request.getAttribute("requestId") + ")";
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(BodyWrappers.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            for (boolean copy : new boolean[] {true, false}) {
                copyBody = copy;
                System.out.println("POST /greet, copyBodyToResponse " + (copy ? "on" : "off"));
                HttpResponse<String> r = http.send(HttpRequest.newBuilder(
                                URI.create("http://localhost:" + port + "/greet"))
                        .header("Content-Type", "application/json")
                        .POST(BodyPublishers.ofString("{\"name\":\"Ana\"}")).build(),
                        BodyHandlers.ofString());
                System.out.println("  client receives: " + r.statusCode() + " \""
                        + r.body() + "\", X-Request-Id "
                        + r.headers().firstValue("X-Request-Id").orElse("-"));
            }
        }
    }
}
Output
POST /greet, copyBodyToResponse on
  logged request : {"name":"Ana"}
  logged response: 200 hello Ana (req-101)
  client receives: 200 "hello Ana (req-101)", X-Request-Id req-101
POST /greet, copyBodyToResponse off
  logged request : {"name":"Ana"}
  logged response: 200 hello Ana (req-102)
  client receives: 200 "", X-Request-Id req-102
  • RequestIdFilter put the id req-101 in two places: a request attribute, which the controller read, and the X-Request-Id response header, which the client received. Setting a header before calling the chain is safe, because nothing has been written yet.
  • ContentCachingRequestWrapper kept a copy of the bytes the controller read, so after the chain the filter could log {"name":"Ana"}. The wrapper caches only what the application actually reads, up to the limit given in the constructor, here 1024 bytes. Spring Framework 7.0 has only the constructor that takes this limit.
  • ContentCachingResponseWrapper collected the response in memory instead of sending it, so the filter could log hello Ana (req-101) before the client saw it.
  • In the second request, the filter logged the response, but the client received 200 with an empty body. The body stayed in the wrapper's buffer, because copyBodyToResponse() was not called. Always call it, in a finally block in production code.

Caching every response in memory costs memory on large downloads and breaks streaming, since nothing reaches the client until the controller finishes. Limit body logging to the paths where you need it, and skip large or binary content types.

Built-in filters worth knowing

Spring ships ready-made filters for common needs, and two of them solve problems that are hard to get right by hand. The program uses ShallowEtagHeaderFilter for caching and ForwardedHeaderFilter for running behind a proxy:

Java
package demo.builtin;

import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.ForwardedHeaderFilter;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@SpringBootApplication
public class BuiltInFilters {

    @Bean
    FilterRegistrationBean<ShallowEtagHeaderFilter> etagFilter() {
        var registration = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
        registration.addUrlPatterns("/catalog");
        return registration;
    }

    @Bean
    ForwardedHeaderFilter forwardedHeaderFilter() {
        return new ForwardedHeaderFilter();   // a Filter bean: registered for /*
    }

    @RestController
    static class Endpoints {
        @GetMapping("/catalog")
        public String catalog() {
            System.out.println("  controller builds the catalog");
            return "[\"lamp\",\"desk\",\"chair\"]";
        }

        @GetMapping("/where")
        public String where(HttpServletRequest request) {
            return "scheme=" + request.getScheme() + ", host=" + request.getServerName()
                    + ", self link=" + ServletUriComponentsBuilder.fromCurrentRequest()
                            .replacePath("/orders/7").toUriString();
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(BuiltInFilters.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String base = "http://localhost:" + port;
            HttpClient http = HttpClient.newHttpClient();

            System.out.println("GET /catalog");
            HttpResponse<String> first = http.send(HttpRequest.newBuilder(
                    URI.create(base + "/catalog")).build(), BodyHandlers.ofString());
            String etag = first.headers().firstValue("ETag").orElseThrow();
            System.out.println("  " + first.statusCode() + " ETag: " + etag
                    + ", body " + first.body().length() + " chars");

            System.out.println("GET /catalog with If-None-Match: " + etag);
            HttpResponse<String> second = http.send(HttpRequest.newBuilder(
                    URI.create(base + "/catalog")).header("If-None-Match", etag).build(),
                    BodyHandlers.ofString());
            System.out.println("  " + second.statusCode() + ", body "
                    + second.body().length() + " chars");

            System.out.println("GET /where directly");
            System.out.println("  " + http.send(HttpRequest.newBuilder(
                    URI.create(base + "/where")).build(), BodyHandlers.ofString()).body()
                    .replace(":" + port, ":PORT"));
            System.out.println("GET /where through a proxy that sets X-Forwarded-*");
            System.out.println("  " + http.send(HttpRequest.newBuilder(
                    URI.create(base + "/where"))
                    .header("X-Forwarded-Proto", "https")
                    .header("X-Forwarded-Host", "shop.example.com")
                    .build(), BodyHandlers.ofString()).body());
        }
    }
}
Output
GET /catalog
  controller builds the catalog
  200 ETag: "0b8eddd992815b90d7e93b5d8668b9167", body 23 chars
GET /catalog with If-None-Match: "0b8eddd992815b90d7e93b5d8668b9167"
  controller builds the catalog
  304, body 0 chars
GET /where directly
  scheme=http, host=localhost, self link=http://localhost:PORT/orders/7
GET /where through a proxy that sets X-Forwarded-*
  scheme=https, host=shop.example.com, self link=https://shop.example.com/orders/7
  • ShallowEtagHeaderFilter buffered the response and added an ETag computed from the body: 0 followed by the MD5 hash of the 23 characters.
  • When the client sent the same value back in If-None-Match, the filter answered 304 Not Modified with an empty body. The controller still built the catalog, as the second controller builds the catalog line shows. The filter saves bandwidth, not server work; to save the work, the controller has to check the ETag itself.
  • Without proxy headers, /where reported http and localhost, the address the request really arrived on. The program prints PORT in place of the random port number.
  • With X-Forwarded-Proto: https and X-Forwarded-Host: shop.example.com, the ForwardedHeaderFilter wrapped the request so that getScheme(), getServerName() and the links built with ServletUriComponentsBuilder use the public address. Without it, an application behind a load balancer returns Location headers and links that point at its internal address.

Only trust forwarded headers from your own proxy, which must overwrite them; otherwise any client can send them and change the links your application builds. In Spring Boot, server.forward-headers-strategy=framework registers this filter for you, and native uses the server's own support. Other filters in Spring include CommonsRequestLoggingFilter for request logging and CorsFilter for CORS.

Traps in filters

  • Exceptions: an exception thrown in a filter does not reach @ExceptionHandler or @RestControllerAdvice, because those belong to the DispatcherServlet, which runs later in the chain. The client gets a 500 from /error. Write the error response in the filter, as the API key filter does; Spring Boot exception handling shows the failure running.
  • Code after the chain: it is skipped when the controller throws, as the first program showed, so put it in a finally block.
  • Committed responses: after chain.doFilter returns, the response is usually already sent, so setting a header or a status there has no effect. Set headers before calling the chain, or wrap the response.
  • Thread-bound state: values put in a ThreadLocal or the logging MDC must be removed in finally, because Tomcat reuses its threads for the next request.
  • Filter state: a filter is a single instance shared by every request, so its fields must be thread-safe, like the AtomicInteger counter in the wrapper example.
  • Asynchronous requests: a controller returning DeferredResult or CompletableFuture causes a second dispatch, of type ASYNC. OncePerRequestFilter skips it by default; a plain Filter registered for that dispatch type would run twice.

Choosing how to write a filter

Filter needs and the approach that fits
NeedUse
Code around every requestA OncePerRequestFilter bean
Only some URLsFilterRegistrationBean with addUrlPatterns, or shouldNotFilter
Run before or after another filter@Order or setOrder; below -100 to run before Spring Security
Also run on error pagessetDispatcherTypes(REQUEST, ERROR)
Reject a requestWrite the response and do not call the chain
Log bodiesContentCachingRequestWrapper and ContentCachingResponseWrapper, with copyBodyToResponse
ETags without controller codeShallowEtagHeaderFilter
Running behind a proxyserver.forward-headers-strategy=framework or native
Authentication and authorizationSpring Security, not a hand-written filter
Logic that needs the controller methodA HandlerInterceptor

Filters are the outermost layer of request handling. For the controllers they wrap, see Spring Boot @RestController.