Recommended Free Tools
In a Spring MVC or Spring Boot application running on the Servlet stack, a Servlet Filter runs at the container level and can inspect or wrap a request and response, perform work around downstream processing, or stop the chain and return a response. The downstream target is usually Spring MVC’s DispatcherServlet. Use a built-in Spring filter when it provides the behavior you need, a custom Servlet Filter for general Servlet-level work, and a Spring Security SecurityFilterChain for authentication and authorization.
This guide reflects the official documentation versions available for this article: Spring Framework 7.0.9, OncePerRequestFilter API 7.0.8, and Spring Framework 6.2.19. Check the documentation matching your project’s resolved dependencies before copying configuration.
What a Servlet Filter does
A Servlet Filter is part of the Servlet container’s request-processing chain. It can run before and after the remaining filters and target servlet, and can wrap request or response objects to modify what downstream components see. Calling chain.doFilter(request, response) passes processing onward; omitting that call lets the filter terminate processing, for example by setting a status and writing a response.
In Spring MVC, requests that reach MVC are typically dispatched to DispatcherServlet. A Servlet Filter therefore operates outside the MVC handler lifecycle: it can apply before a controller is selected and after the downstream processing returns. For the Servlet API contract and Spring’s filter support, see the Spring Framework Filters reference.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
The around-chain shape
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Work before downstream processing
chain.doFilter(request, response);
// Work after downstream processing
}
Code after chain.doFilter runs when downstream processing returns normally. If downstream code throws an exception, use try/finally when cleanup must happen regardless; do not assume the response is still writable or uncommitted after the chain returns.
Choose the right Spring mechanism
| Mechanism | Good fit | Decide by checking |
|---|---|---|
| Built-in Spring filter | A documented feature such as form-content handling, forwarded headers, shallow ETags, CORS, or URL handling. | Whether its exact behavior suits the requirement and is documented for your Framework version. |
Custom Servlet Filter or GenericFilterBean |
Servlet-level request or response work that should surround downstream processing. | Bean lifecycle, registration, URL scope, dispatcher types, ordering, and whether the filter wraps or terminates the chain. |
OncePerRequestFilter subclass |
Custom HTTP-aware filtering that benefits from an already-filtered marker and explicit async/error dispatch choices. | Invocation on each dispatch, container dispatcher-type registration, thread-context setup, and duplicate registration. |
Spring Security SecurityFilterChain |
Authentication, authorization, exploit protection, and security-context handling. | Chain matcher specificity and order, filter order, and coverage of every URL that must be secured. |
| Spring MVC interceptor | MVC handler-level concerns tied to MVC processing. | Whether the concern belongs to the handler lifecycle rather than the Servlet container. It is not interchangeable with a Servlet Filter. |
Prefer a built-in filter when it matches
Spring Framework provides filters for common Servlet web concerns, including form content, forwarded headers, shallow ETags, CORS, and URL handling. A built-in component can avoid reimplementing behavior, but its name alone does not prove it matches your use case. Check the version-specific Filters reference for its scope and configuration.
Use a custom filter for general Servlet-level work
GenericFilterBean adapts a Servlet Filter to Spring’s bean lifecycle facilities. Spring Framework documents Servlet filter declaration through Servlet configuration mechanisms; in Spring Boot, filter beans are configured by Boot. Confirm the filter’s URL mapping, dispatcher types, and ordering, and ensure it is registered only in the intended chain.
Rank #2
Use Spring Security for security behavior
Authentication, authorization, exploit protection, and security-context handling belong in Spring Security’s filter architecture. Configure these concerns with HttpSecurity and a SecurityFilterChain bean rather than casually registering a security filter as an ordinary container filter. The architecture and chain behavior are described in the Spring Security Servlet architecture reference.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Registering and understanding a custom filter
Filter behavior depends not just on its implementation but also on where and when it is registered. In Spring Boot, a filter bean is configured by Boot; Servlet configuration mechanisms are also available. Check the registration’s URL patterns, dispatcher types, and order against the application’s actual needs. If the same filter is registered with the container and added to Spring Security, it may run twice or at an unexpected point.
- Scope: Verify which URLs the registration covers.
- Dispatch types: Check whether it runs for REQUEST, ASYNC, or ERROR dispatches, as applicable.
- Order: Establish which filters must run before or after it, and why.
- Ownership: Decide whether it belongs to the general container chain or to Spring Security’s chain; avoid accidental registration in both.
How OncePerRequestFilter handles dispatches
OncePerRequestFilter is a Spring base class with a doFilterInternal hook and controls for async and error dispatches. Its “once” guarantee is about a request dispatch, not an unconditional promise that a filter’s code runs exactly once over every stage of a request’s lifetime. Servlet dispatch type registration also determines whether the container invokes the filter for a dispatch at all.
Rank #3
The API discusses REQUEST, ASYNC, and ERROR dispatches. Decide explicitly which ones your filter should handle, use the class’s dispatch controls accordingly, and align the container registration. Async processing can involve another dispatch, potentially on another thread; thread-local context that was set during the initial dispatch may need deliberate initialization again. See the versioned OncePerRequestFilter API for its precise behavior and controls.
Configure Spring Security chains precisely
Spring Security’s central Servlet entry point is FilterChainProxy. It selects the first matching SecurityFilterChain, then runs that chain’s filters in order. It also applies the HttpFirewall and clears the SecurityContext to help prevent memory leaks. The chain is assembled according to enabled features and configuration, so no one filter order should be treated as universal.
Chain selection and authorization are different
securityMatcher determines whether a SecurityFilterChain applies to a request. requestMatchers inside authorization configuration determine which authorization rule applies after a chain has been selected. A request that matches no security chain is not protected by Spring Security.
For example, this configuration selects one chain for /api/**, then defines authorization rules within it:
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/**")
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated());
return http.build();
}
This is illustrative, not a complete application security policy: authentication mechanisms and any other required protections must be configured for the application. If the application defines multiple chains, put more specific chains before broader ones and provide coverage for all paths that should be secured. Consult the Spring Security Java configuration reference and the Servlet architecture reference.
Filter order is a dependency, not decoration
Filters in a security chain execute in an order that affects behavior. For example, authentication must occur before authorization can evaluate an authenticated principal. Place a custom security filter relative to other filters only when its dependencies justify that position, and inspect the resulting chain rather than assuming an example order applies to every configuration.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteForwarded headers require a trust boundary
Forwarded headers can tell an application about the original client-facing scheme, host, or address when a proxy sits in front of it. Those values are safe to use only when the deployment controls who supplies them. A client may send forged forwarded headers directly unless the trusted edge proxy resets the relevant headers before forwarding the request.
Spring Framework’s forwarded-header guidance warns: “For maximum security, a proxy at the edge of trust must be configured to reset both the standard …” The published guidance should be read in full for the relevant header details. Configure a deliberate forwarded-header strategy only when the application is behind a trusted proxy that sanitizes client-supplied values.
Debug filter behavior and ordering
- Identify the request path and dispatch. Establish the URL and whether processing is a REQUEST, ASYNC, or ERROR dispatch; these facts affect filter mapping and invocation.
- Confirm registration ownership. Determine whether the filter is registered by the Servlet container/Boot, added to Spring Security, or both.
- Inspect the security chain selection. For security issues, start with
FilterChainProxyand identify the first matchingSecurityFilterChain. - Inspect the actual filter list. Print or inspect the filters in the selected chain for the request. Compare their order with the dependencies of the behavior being diagnosed.
- Check coverage and order. Verify URL patterns, dispatcher types, chain matchers, and authorization matchers independently.
For security architecture details, including FilterChainProxy, see the official Spring Security reference. For Framework filters and registration considerations, use the Spring Framework Filters reference for the version resolved by the project.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

