springboot配置多个Filter过滤器,指定不同的过滤地址,并指定过滤顺序

springboot配置过滤器的两种方式

1.使用注解@WebFilter、@Component。springboot将会自动注册过滤器,但是使用了@Component注解之后,自测urlPatterns将会无效,不管你写成什么拦截地址,最后查看控制台日志,过滤器注册的地址都是"/*"

@Component
@WebFilter(
    filterName = "AuthFilter",
    urlPatterns = {"/*"}
)
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {


    }


    @Override
    public void destroy() {

    }
}

2.使用注册Bean的方式,可以指定过滤器的过滤地址,还可通过Order指定过滤顺序。setOrder()的值越小优先级越高
 

/**
 * 需要配置的bean
 */
@Configuration
public class ProjectConfiguration {

    @Bean
    public FilterRegistrationBean registrationProjectFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(this.getProjectFilter());
        registration.addUrlPatterns("/project/*");
        registration.setOrder(2);
        return registration;
    }

    @Bean
    public ProjectFilter getProjectFilter(){
        return new ProjectFilter();
    }

    @Bean
    public FilterRegistrationBean registrationAuthFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(this.getAuthFilter());
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        return registration;
    }

    @Bean
    public AuthFilter getAuthFilter(){
        return new AuthFilter();
    }
}

 

你可能感兴趣的:(springboot配置多个Filter过滤器,指定不同的过滤地址,并指定过滤顺序)