Spring Boot Filter
Filter
In Spring boot, we can use Java Servlet filter.
The way to implement filter is same.
Implement Filter interface
Use JavaServlet Filter
To use this, we need to register Filter using Configuration.
Please prepare configuration class
Filter class
public class SampleFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); } @Override public void destroy() { } }
Configuration
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean firstFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); SampleFilter sampleFilter = new SampleFilter(); registrationBean.setFilter(sampleFilter); registrationBean.setOrder(1); List<String> urlPatterns = new ArrayList<String>(); urlPatterns.add("/*"); registrationBean.setUrlPatterns(urlPatterns); return registrationBean; } }
Multiple Filter and Order Example
Add 2 in the same configuration and setOrder
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean firstFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); SampleFilter sampleFilter = new SampleFilter(); registrationBean.setFilter(sampleFilter); registrationBean.setOrder(1); List<String> urlPatterns = new ArrayList<String>(); urlPatterns.add("/*"); registrationBean.setUrlPatterns(urlPatterns); return registrationBean; } @Bean public FilterRegistrationBean secondFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); SampleFilter2 sampleFilter = new SampleFilter2(); registrationBean.setFilter(sampleFilter); registrationBean.setOrder(2); List<String> urlPatterns = new ArrayList<String>(); urlPatterns.add("/*"); registrationBean.setUrlPatterns(urlPatterns); return registrationBean; } }