Mastering Spring Boot Filters: From Basics to CORS Solutions
This article explains the role of Servlet Filters in Spring Boot, details their execution chain, shows how to implement custom filters, and provides step‑by‑step configurations using FilterRegistrationBean and @WebFilter, including a practical CORS filter example.
Introduction
The previous article covered Spring Boot interceptors; this piece focuses on Filters, a core Servlet technology used for URL‑level permission control, sensitive‑word filtering, response compression, and other advanced functions.
What Is a Filter?
A Filter intercepts requests and responses managed by the web server, allowing developers to modify headers, block or transform traffic, and perform cross‑cutting concerns such as security checks.
Filter Execution Principle
When a client requests a web resource, the server evaluates the filter chain defined in the configuration. Each filter’s doFilter() method runs in order; the request can be altered, blocked, or passed to the next filter. After the target resource processes the request, the response travels back through the chain, allowing filters to modify the output.
Creating a Custom Filter
@Component
public class CrosFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// Continue to the next filter
chain.doFilter(req, response);
}
}Configuring Filters in Spring Boot
Bean Registration (Recommended)
@Configuration
public class FilterConfig {
@Autowired
private Filter1 filter1;
@Autowired
private Filter2 filter2;
/** Inject Filter1 */
@Bean
public FilterRegistrationBean filter1() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter1);
registration.addUrlPatterns("/*");
registration.setName("filter1");
// Set execution order
registration.setOrder(1);
return registration;
}
/** Inject Filter2 */
@Bean
public FilterRegistrationBean filter2() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter2);
registration.addUrlPatterns("/*");
registration.setName("filter2");
// Set execution order
registration.setOrder(2);
return registration;
}
}Note: The order value determines the sequence in which filters are invoked.
Using @WebFilter
@WebFilter(filterName = "crosFilter", urlPatterns = {"/*"})
public class CrosFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// Continue to the next filter
chain.doFilter(req, response);
}
}To activate @WebFilter, add @ServletComponentScan to a configuration class or the main application class.
@SpringBootApplication
@ServletComponentScan(value = {"com.example.springbootintercept.filter"})
public class SpringbootApplication {}Practical Example: CORS Filter
Cross‑origin requests are a common challenge in front‑back separation. A simple filter can add the necessary response headers.
@Component
public class CrosFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
// Continue to the next filter
chain.doFilter(req, response);
}
}Register the filter with highest precedence:
@Configuration
public class FilterConfig {
@Autowired
private CrosFilter crosFilter;
/** Inject crosFilter */
@Bean
public FilterRegistrationBean crosFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(crosFilter);
registration.addUrlPatterns("/*");
registration.setName("crosFilter");
// Set highest precedence
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
}Conclusion
Filters are relatively simple but indispensable in real‑world development; frameworks such as Apache Shiro and Spring Security rely heavily on them. Understanding filter creation and registration lays a solid foundation for deeper security and request‑processing studies.
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.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
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.
