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.FilterdoFilter(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)DispatcherServletchain.doFilter
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
| Way | Applies to | Best for |
|---|---|---|
Filter@Component@Bean | All URLs, REQUEST | Simple filters for the whole application |
OncePerRequestFilter | Same, but at most once per request | Most filters written for Spring applications |
FilterRegistrationBean | Chosen URL patterns, order, dispatcher types | Filters that apply to part of the application |
@WebFilter@ServletComponentScan | What the annotation says | Code shared with plain servlet applications |
Spring Security's SecurityFilterChain | Paths matched by its rules | Anything 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
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 FilterOncePerRequestFilterfinally
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);
}
}
}
}
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
bean and registered it with Tomcat forFilter , sorted by/* . It also added three filters of its own:@Order first of all, so that request parameters are decoded as UTF-8, thencharacterEncodingFilter andformContentFilter .requestContextFilter - For
, 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./hello - For
, the controller threw, and the exception travelled back up through/boom .chain.doFilter never printed itsPlainFilter line, because its code after the call was skipped. Onlyout , which usedOnceFilter , ran its closing code. Code that must always run, such as clearing afinally or recording a metric, belongs inThreadLocal .finally - In that
block the status was still 200, although the client received 500. The error status is set later, by Tomcat, when it handles the exception.finally - Tomcat then forwarded the request to
, as a second pass through the chain with the dispatcher type/error . OnlyERROR ran again, because it was registered witherrorAwareFilter . Spring Boot registers ordinaryDispatcherType.ERROR beans forFilter only.REQUEST
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
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/api/*shouldNotFilter
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());
}
}
}
}
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
. The controller never ran, and nothing later in the chain saw the request.chain.doFilter - With the right key, the filter passed the request on and the controller answered 200.
matched the URL pattern, but/api/public/status returnedshouldNotFilter , so the filter skipped it. This hook oftrue is clearer than anOncePerRequestFilter at the top ofif .doFilterInternal is outside/home , so Tomcat never called the filter at all./api/*
The filter class has no @Component@ComponentFilterRegistrationBean/api/x/*/api/**.json{id}
A FilterRegistrationBeansetEnabled(false)
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:
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("-"));
}
}
}
}
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
put the idRequestIdFilter in two places: a request attribute, which the controller read, and thereq-101 response header, which the client received. Setting a header before calling the chain is safe, because nothing has been written yet.X-Request-Id kept a copy of the bytes the controller read, so after the chain the filter could logContentCachingRequestWrapper . 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.{"name":"Ana"} collected the response in memory instead of sending it, so the filter could logContentCachingResponseWrapper before the client saw it.hello Ana (req-101)- 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
was not called. Always call it, in acopyBodyToResponse() block in production code.finally
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 ShallowEtagHeaderFilterForwardedHeaderFilter
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());
}
}
}
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
buffered the response and added anShallowEtagHeaderFilter computed from the body:ETag followed by the MD5 hash of the 23 characters.0- When the client sent the same value back in
, the filter answered 304 Not Modified with an empty body. The controller still built the catalog, as the secondIf-None-Match line shows. The filter saves bandwidth, not server work; to save the work, the controller has to check the ETag itself.controller builds the catalog - Without proxy headers,
reported/where andhttp , the address the request really arrived on. The program printslocalhost in place of the random port number.PORT - With
andX-Forwarded-Proto: https , theX-Forwarded-Host: shop.example.com wrapped the request so thatForwardedHeaderFilter ,getScheme() and the links built withgetServerName() use the public address. Without it, an application behind a load balancer returnsServletUriComponentsBuilder headers and links that point at its internal address.Location
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=frameworknativeCommonsRequestLoggingFilterCorsFilter
Traps in filters
- Exceptions: an exception thrown in a filter does not reach
or@ExceptionHandler , because those belong to the@RestControllerAdvice , which runs later in the chain. The client gets a 500 fromDispatcherServlet . Write the error response in the filter, as the API key filter does;/errorSpring 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
block.finally - Committed responses: after
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.chain.doFilter - Thread-bound state: values put in a
or the logging MDC must be removed inThreadLocal , because Tomcat reuses its threads for the next request.finally - Filter state: a filter is a single instance shared by every request, so its fields must be thread-safe, like the
counter in the wrapper example.AtomicInteger - Asynchronous requests: a controller returning
orDeferredResult causes a second dispatch, of typeCompletableFuture .ASYNC skips it by default; a plainOncePerRequestFilter registered for that dispatch type would run twice.Filter
Choosing how to write a filter
| Need | Use |
|---|---|
| Code around every request | A OncePerRequestFilter |
| Only some URLs | FilterRegistrationBeanaddUrlPatternsshouldNotFilter |
| Run before or after another filter | @OrdersetOrder |
| Also run on error pages | setDispatcherTypes(REQUEST, ERROR) |
| Reject a request | Write the response and do not call the chain |
| Log bodies | ContentCachingRequestWrapperContentCachingResponseWrappercopyBodyToResponse |
| ETags without controller code | ShallowEtagHeaderFilter |
| Running behind a proxy | server.forward-headers-strategy=frameworknative |
| Authentication and authorization | Spring Security, not a hand-written filter |
| Logic that needs the controller method | A |
Filters are the outermost layer of request handling. For the controllers they wrap, see