Understanding SpringBoot Filters and Their Place in the Request Chain
The article explains what SpringBoot Filters are, their core methods, three registration approaches, practical examples such as encoding, logging, and request blocking, the execution order among multiple filters, a full request chain overview, and a detailed comparison with Interceptors, concluding with usage recommendations.
1. What Is a Filter?
Filter is a component defined by the Servlet specification that runs in the Tomcat container layer. It can preprocess and postprocess all requests, modify request/response headers, set unified encoding, handle global CORS, logging, rate limiting, risk control, and sensitive‑word filtering.
Pre‑processing and post‑processing of requests
Filter/modify request and response headers
Unified character encoding
Global cross‑origin handling
Logging, rate limiting, risk control
Sensitive‑word filtering
2. Core Methods
Implement the Filter interface and override three methods: init, doFilter, and destroy. In most scenarios only doFilter needs custom logic.
public interface Filter {
void init(FilterConfig filterConfig) throws Exception;
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception;
void destroy();
}3. Three Ways to Register a Filter in SpringBoot
Method 1: @WebFilter
@WebFilter(urlPatterns = "/*", filterName = "demoFilter")
public class DemoFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception {
// filter logic
chain.doFilter(request, response); // allow
}
}
@ServletComponentScan // scans @WebFilter
@SpringBootApplication
public class App { }Method 2: JavaConfig Registration
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<DemoFilter> demoFilter() {
FilterRegistrationBean<DemoFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(new DemoFilter());
bean.addUrlPatterns("/*");
bean.setOrder(1); // smaller number executes earlier
return bean;
}
}Method 3: Component Auto‑Registration
@Component
@Order(1)
public class DemoFilter implements Filter { }4. Unified Encoding Filter Example
@WebFilter("/*")
public class EncodingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
chain.doFilter(request, response);
}
}5. Request Logging Filter Example
@Slf4j
@WebFilter("/*")
public class LogFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws Exception {
HttpServletRequest request = (HttpServletRequest) req;
log.info("Request URI: {}", request.getRequestURI());
log.info("Method: {}", request.getMethod());
chain.doFilter(req, resp);
}
}6. Blocking Illegal Requests (Anti‑Hotlink, Blacklist)
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws Exception {
HttpServletRequest request = (HttpServletRequest) req;
String ip = request.getRemoteAddr();
if (blackList.contains(ip)) {
resp.getWriter().write("非法请求");
return;
}
chain.doFilter(req, resp);
}7. Wrapping Request for Repeated Reads
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws Exception {
RepeatedReadRequestWrapper wrapper = new RepeatedReadRequestWrapper((HttpServletRequest) req);
chain.doFilter(wrapper, resp);
}Typical scenarios: logging, signature verification, global encryption/decryption.
8. Execution Order of Multiple Filters
Rule: the smaller the Order value, the earlier the filter executes.
Request → Filter1 → Filter2 → Controller → Filter2 → Filter1 → Response9. Complete SpringBoot Request Chain
Tomcat
Filter (Servlet layer)
Spring DispatcherServlet Interceptor (preHandle)
Controller
Interceptor (postHandle)
View rendering
Interceptor (afterCompletion)
Filter post‑processing
Response
In short: Filter first, Interceptor in the middle, Controller last.
10. Filter vs Interceptor Comparison
Specification: Filter – Servlet; Interceptor – Spring MVC.
Scope: Filter intercepts all requests (including static resources); Interceptor only intercepts controller requests.
Timing: Filter runs earlier at the container level; Interceptor runs later within Spring.
Bean access: Filter cannot obtain Spring beans; Interceptor can.
Both can abort a request.
Typical use cases: Filter – encoding, CORS, rate limiting; Interceptor – authentication, permission checks, logging.
11. Usage Recommendations
Use Filter for unified encoding, CORS, rate limiting, risk control, request logging.
Use Interceptor for login authentication, permission verification, interface logging.
Use Controller + AOP for parameter validation and response wrapping.
12. Summary
Filter is a Servlet component that intercepts all requests.
Core method: doFilter.
Register via @WebFilter or FilterRegistrationBean.
Execution order is determined by Order (smaller first).
Request flow: Filter → Interceptor → Controller.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Workshop
Focused on Java backend technologies, sharing fundamentals, multithreading, JVM, the Spring ecosystem, microservices, distributed systems, high concurrency, source‑code analysis, and practical experience. Continuously delivers high‑quality original content, interview guides, and learning roadmaps to help Java developers progress from beginner to advanced, enhancing technical skills and core competitiveness.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
