0
Follow
0
View

How do I configure Filter in Spring Boot?

danzw123 注册会员
2023-01-25 16:09

1. Using @Bean injection in the configuration class [recommended]
is actually very simple. You just need to inject an instance of FilterRegistrationBean into the IOC container as follows:

@Configuration
public class FilterConfig {
@Autowired
private Filter1 filter1;
@Autowired
private Filter2 filter2;
/**
* 注入Filter1
* @return
*/
@Bean
public FilterRegistrationBean filter1() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter1);
registration.addUrlPatterns("/*");
registration.setName("filter1");
//设置优先级别
registration.setOrder(1);
return registration;
}
/**
* 注入Filter2
* @return
*/
@Bean
public FilterRegistrationBean filter2() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter2);
registration.addUrlPatterns("/*");
registration.setName("filter2");
//设置优先级别
registration.setOrder(2);
return registration;
}
}

Note: The priority level set determines the order in which filters are executed. 2. Use @WebFilter
@WebFilter is a Servlet3.0 annotation for annotating a Filter. Spring Boot also supports this method. Just annotate the comment on the
custom Filter as follows:

@WebFilter(filterName = "crosFilter",urlPatterns = {"/*"})
public class CrosFilter implements Filter {
//重写其中的doFilter方法
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws
IOException, ServletException {
//继续执行下一个过滤器
chain.doFilter(req, response);
}
}

For the @WebFilter annotation to work, you need to annotate another annotation on the configuration class @ServletComponentScan to scan it for
effect, as follows:

@SpringBootApplication
@ServletComponentScan(value = {"com.example.springbootintercept.filter"})
public class SpringbootApplication {}

At this point, the configuration is complete, the project is up and running.