Spring Boot 如何在Sping Boot 应用程序中定义Servlet过滤器的执行顺序

8e2ybdfx  于 2023-04-30  发布在  Spring
关注(0)|答案(3)|浏览(156)

我试图在我的Sping Boot 应用程序中设置2个具有相同URLMap的过滤器的执行顺序。我试着在我的主应用程序类中使用2个过滤器注册bean,如下所示,但没有工作。我希望先击中authorizationFilter,然后再击中validationFilter。但是,当两者都配置时,它总是只命中validationFilter。如果我注解掉validationFilter,它会命中authorizationFilter

@Bean
public FilterRegistrationBean authorizationFilter(){
    FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
    filterRegBean.setFilter(authorizationFilter);
    List<String> urlPatterns = new ArrayList<String>();
    urlPatterns.add("/v1/*");
    filterRegBean.setUrlPatterns(urlPatterns);
    return filterRegBean;
}

@Bean
public FilterRegistrationBean validationFilter(){
    FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
    filterRegBean.setFilter(validationFilter);
    List<String> urlPatterns = new ArrayList<String>();
    urlPatterns.add("/v1/*");
    filterRegBean.setUrlPatterns(urlPatterns);
    return filterRegBean;
}

我还尝试引入web.xml并将可执行jar转换为war文件。

<web-app>   
<filter>
    <filter-name>authorizationFilter</filter-name>
    <filter-class>com.security.filter.AuthorizationFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>authorizationFilter</filter-name>
    <url-pattern>/v1/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>validationFilter</filter-name>
    <filter-class>com.security.validation.ValidationFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>validationFilter</filter-name>
    <url-pattern>/v1/*</url-pattern>
</filter-mapping>
</web-app>

但应用程序似乎无法识别Web。xml,因为它只命中具有上述配置的验证过滤器。我感谢任何参与解决这个问题。谢谢

j2cgzkjk

j2cgzkjk1#

setOrder(int)方法完成任务。
下面是一个例子

@Configuration
@EnableAutoConfiguration
@EnableWebMvc
@ComponentScan
public class Application {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        SecurityFilter securityFilter = new SecurityFilter();
        registrationBean.setFilter(securityFilter);
        registrationBean.setOrder(2);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean contextFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        RequestContextFilter contextFilter = new RequestContextFilter();
        registrationBean.setFilter(contextFilter);
        registrationBean.setOrder(1);
        return registrationBean;
    }
}
wlzqhblo

wlzqhblo2#

Sping Boot 使用AnnotationAwareOrderComparatorFilterRegistrationBean进行排序,然后将它们应用到servlet上下文。RegistrationBean当前不是Ordered,因此无法通过调用方法来设置顺序,但您可以通过创建子类并将@Order添加到它们来解决这个问题。我认为在框架中创建基类Ordered并提供一个setter可能是一件很有用的事情(如果你同意的话,在github上打开一个issue)。
更新:Ordered已在1中添加。0.x。

lsmepo6l

lsmepo6l3#

Bean名称将解决您的问题:@Bean(“aFilter”)。

相关问题