Quick revision
The short answer
Each filter receives the request, the response and the FilterChain, and decides whether to call chain.doFilter to pass the request on to the next filter and eventually the servlet. If it does not call doFilter, processing stops there, for example when authentication fails and the filter writes a 401 response itself; code after the doFilter call runs once the rest of the chain has returned, which is where filters add headers or measure timing. Order matters because later filters depend on what earlier ones did, such as authorisation needing authentication to have run, and Spring MVC's HandlerInterceptor follows the same idea, stopping the chain when preHandle returns false.
What to remember
In this answer, we saw that servlet filters are a chain of responsibility: each filter gets the request and the FilterChain and continues by calling chain.doFilter, or stops by writing the response itself, as an authentication filter does with a 401. Code after doFilter runs on the way back, for timing and headers. Order matters because later filters, such as Spring Security's AuthorizationFilter, depend on earlier ones like authentication, and HandlerInterceptor applies the same idea in Spring MVC with preHandle returning false to stop.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Each filter receives the request, the response and the FilterChain, and decides whether to call chain.doFilter to pass the request on to the next filter and eventually the servlet. If it does not call doFilter, processing stops there, for example when authentication fails and the filter writes a 401 response itself; code after the doFilter call runs once the rest of the chain has returned, which is where filters add headers or measure timing. Order matters because later filters depend on what earlier ones did, such as authorisation needing authentication to have run, and Spring MVC's HandlerInterceptor follows the same idea, stopping the chain when preHandle returns false.
Why this question is asked
Every request to a Spring web application passes through a line of filters before it reaches our controller: character encoding, security, CORS, request logging and more. When a request is rejected with a 401 that we did not expect, or a header is missing, or a filter seems to do nothing, the explanation is almost always in how the chain passes requests along and in what order. Interviewers ask this to see whether we understand the chain of responsibility pattern from the inside, because that understanding is what lets us debug security configuration. In this answer, we will recap the pattern, follow a request through a filter that continues and one that stops, look at the code that runs on the way back, explain why order matters in Spring Security, and compare with HandlerInterceptor.
1A Quick Recap of Chain of Responsibility
In the chain of responsibility pattern, a request is passed along a chain of handlers. Each handler looks at the request and decides: handle it itself and stop, or do some work and pass it to the next handler. The sender does not know which handler will finally deal with it, and handlers can be added, removed or reordered without changing the sender.
Servlet filters are a direct implementation. The servlet container builds a chain of jakarta.servlet.Filter objects (javax.servlet.Filter before Jakarta EE 9) for each request, ending at the servlet. Each filter's doFilter(request, response, chain) method gets the chain object, and the filter itself decides whether to call chain.doFilter(request, response), which invokes the next filter, or the servlet when no filters are left.
2Continuing or Stopping the Chain
Here is a filter that checks an API key. When the key is valid it passes the request on; when it is missing, it stops the chain by writing the response itself and returning without calling doFilter.
9 messages in order. Play them, or step through them one at a time.
Notice that stopping is simply not calling the next element. Nothing else in the chain is informed; the call returns back through the filters that already ran, and the container sends the response. This is also how Spring Security's filters reject requests: when authentication is required and missing, the ExceptionTranslationFilter starts the authentication entry point, which typically answers 401 or redirects to a login page, without the request ever reaching the DispatcherServlet.
3Code That Runs on the Way Back
Because chain.doFilter is an ordinary method call, it returns when everything after it in the chain has finished, including the controller. So code after the call runs on the way back, with the response already produced. That is where filters measure timing, add response headers, or clean up thread-local data in a finally block so that it does not leak to the next request on the same thread.
But there is a catch for headers: once the response is committed, meaning its headers have been sent to the client, which happens when the body grows past the buffer or the controller flushes it, headers added afterwards are silently ignored. Filters that must add headers usually set them before calling doFilter, or wrap the response.
4Why Order Matters
Filters depend on each other's work, so their order is part of their correctness. In Spring Security, the filter chain is itself a chain inside one servlet filter, the FilterChainProxy, and its filters run in a fixed, documented order. Filters that load the security context come first, then authentication filters such as the one for bearer tokens, BearerTokenAuthenticationFilter, or for forms and HTTP Basic, then ExceptionTranslationFilter, and near the end AuthorizationFilter, which decides whether the authenticated user may access the URL.
Authorisation needs authentication to have run first: AuthorizationFilter reads the Authentication from the SecurityContext, which the earlier filters filled. If a custom authentication filter is placed after AuthorizationFilter, every request is checked while still anonymous and is denied, even with a valid token. Similarly, a CORS filter must run before authentication, or browser preflight requests, which carry no credentials, are rejected with 401 before CORS headers are added. That is why HttpSecurity offers addFilterBefore and addFilterAfter relative to known filter classes, rather than absolute positions.
- Security context loadingRestore any existing Authentication
- CORS and header filtersPreflight answered before authentication
- Authentication filtersBearer token, form login, HTTP Basic, custom
- ExceptionTranslationFilterTurns access errors into 401 or 403
- AuthorizationFilterNeeds the Authentication set above
- DispatcherServletController runs only if all passed
6 layers, from the top down. Step through them one at a time.
Simplified; check your Spring Security version's documentation for the full list.
5HandlerInterceptor: The Same Idea Inside Spring MVC
Inside the DispatcherServlet, Spring MVC has its own chain of HandlerInterceptor objects around each controller call. An interceptor's preHandle method returns a boolean instead of calling a chain object: true means continue, and false means stop, in which case the interceptor is expected to have written the response itself. postHandle runs after the controller but before the view is rendered, and afterCompletion runs at the very end, even after exceptions, which makes it the place for cleanup.
Interceptors know which controller method will handle the request, so they suit checks that depend on the handler, such as reading an annotation on the method. Filters run earlier, for every request including static resources and errors, so they suit cross-cutting concerns like security, encoding and logging.
6Follow-up questions
What happens if a filter calls chain.doFilter twice?
The rest of the chain, including the controller, runs twice for the same request, which usually produces an error because the response has already been written or committed. A filter must call doFilter at most once on each path through its code.
How do you set the order of plain servlet filters in Spring Boot?
For filter beans, Spring Boot uses the @Order annotation or the Ordered interface, or the order of a FilterRegistrationBean, where lower values run first. Spring Security's whole chain is registered as one filter with its own order, and filters inside it are ordered through HttpSecurity.
Why extend OncePerRequestFilter instead of implementing Filter?
A request can pass through the filter chain more than once, for example on a forward or an error dispatch. OncePerRequestFilter marks the request with an attribute so that its doFilterInternal runs only once per request, and it gives a typed HTTP request and response.
7Conclusion
In this answer, we saw that servlet filters are a chain of responsibility: each filter gets the request and the FilterChain and continues by calling chain.doFilter, or stops by writing the response itself, as an authentication filter does with a 401. Code after doFilter runs on the way back, for timing and headers. Order matters because later filters, such as Spring Security's AuthorizationFilter, depend on earlier ones like authentication, and HandlerInterceptor applies the same idea in Spring MVC with preHandle returning false to stop.
Open with
Servlet filters are a textbook chain of responsibility. For each request, the container builds a chain of filters ending at the servlet. Each filter's doFilter gets the request, the response and the FilterChain, and it decides what happens next.
Then, if they want more
If it calls chain.doFilter, the request goes to the next filter and eventually to the DispatcherServlet and the controller. If it does not call it, processing stops right there. That is how an authentication filter rejects a request: it writes a 401 and returns without calling doFilter, so the controller never runs.
Because doFilter is a normal method call, code after it runs on the way back, once the rest of the chain is done, which is where we log timing or clean up the MDC in a finally block. Order matters because filters depend on each other.
In Spring Security, the filters inside the FilterChainProxy run in a defined order: authentication filters populate the SecurityContext, and AuthorizationFilter near the end reads it to decide access. If I put my custom token filter after AuthorizationFilter, every request is still anonymous when it is checked and gets denied.
That is why we use addFilterBefore or addFilterAfter relative to known filter classes. Spring MVC's HandlerInterceptor is the same idea one level deeper: preHandle returns true to continue or false to stop, postHandle runs after the controller, and afterCompletion always runs at the end.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Jakarta EE 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Servlet filters and the Spring Security filter chain follow the chain of responsibility...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/477be4245c/