SpringBoot过滤器

配置多个过滤器

  • 每个过滤器都配置成bean
@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean registFilter(){
        FilterRegistrationBean registration = new FilterRegistrationBean();

        //配置认证过滤器
        registration.setFilter(new CASFilterExtend());
        registration.setName("CAS Filter");
        //设置过滤器的参数
        registration.addInitParameter("casserverLoginIP","192.168.1.128:8080");

        registration.addUrlPatterns("/*");
        //设置优先级
        registration.setOrder(9);
        return registration;
    }

    @Bean
    public FilterRegistrationBean testFilter(){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        //测试的过滤器
        registration.setFilter(new MyTestFilter());
        registration.addUrlPatterns("/*");
        registration.setOrder(3);
        return registration;
    }
}
  • 过滤器的优先级
    数字越低优先级越高
  • 自定义过滤器
    通过实现Filter接口 在doFilter中进行过滤条件设置
public class MyTestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入测试过滤器中");
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

你可能感兴趣的:(SpringBoot过滤器)