1、创建一个自定义过滤器
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// TODO 过滤器要做的事情
// 将请求传递到下一个过滤器
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
2、注册自定义过滤器
2.1、通过@WebFilter注解
添加注解@WebFilter
@WebFilter(urlPatterns = "/*", filterName = "myFilter")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// TODO 过滤器要做的事情
// 将请求传递到下一个过滤器
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
缺点:不能设置过滤器之间的优先级
2.2、通过FilterRegistrationBean注册
在配置类中创建FilterRegistrationBean
@Bean
public FilterRegistrationBean<Filter> filterRegistrationBean(SecurityManager securityManager,UserService userService) throws Exception{
FilterRegistrationBean<Filter> filterRegistration = new FilterRegistrationBean<Filter>();
// 注册一个filter,需要new或者spring自动装配
filterRegistration.setFilter(filter);
// 设置过滤器的名字,如果不指定,将使用bean的名字
filterRegistration.setName("myFilter");
// 设置过滤规则
filterRegistration.addUrlPatterns("/*");
// 让spring来管理过滤器的生命周期而不是让tomcat,默认true
filterRegistration.addInitParameter("targetFilterLifecycle", "true");
// 开启异步支持,默认true
filterRegistration.setAsyncSupported(true);
// 启用过滤器,默认true
filterRegistration.setEnabled(true);
// 设置调度程序类型
filterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
// 设置优先级
filterRegistration.setOrder(1);
return filterRegistration;
}