springboot配置Filter

基本配置

方法一:注解方式

@Component
@WebFilter(urlPatterns = "/*", filterName = "FirstFilter")
public class FirstFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("FirstFilter 执行");
        filterChain.doFilter(servletRequest, servletResponse);
    }

}

方法二:配置类

@Configuration
public class FilterConfig{

    @Bean
    public FilterRegistrationBean firstFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new FirstFilter());
        // 过滤器这里用/* 而不是/**,否则不生效
        registration.addUrlPatterns("/*");
        registration.setName("firstFilter");
        return registration;
    }
}

配置多个并指定顺序

方法一:注解方式

可以给过滤器类添加 @Order 注解,或实现 Ordered 接口,值越小优先级越高

@Order(1)
@Component
@WebFilter(urlPatterns = "/*", filterName = "FirstFilter")
public class FirstFilter implements Filter, Ordered {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("FirstFilter 执行");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

方法二:配置类

@Configuration
public class FilterConfig{
    @Bean
    public FilterRegistrationBean secondFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new SecondFilter());
        // 过滤器这里用/* 而不是/**,否则不生效
        registration.addUrlPatterns("/*"); 
        registration.setName("secondFilter");
        registration.setOrder(2);
        return registration;
    }

    @Bean
    public FilterRegistrationBean firstFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new FirstFilter());
        registration.addUrlPatterns("/*");
        registration.setName("firstFilter");
        // 在配置类中设置顺序的方法,@Order注解不生效
        registration.setOrder(1);
        return registration;
    }
}
posted @ 2022-05-07 22:13  originyuan  阅读(357)  评论(0编辑  收藏  举报