4

有没有办法禁用嵌入式 Servlet 过滤器?

我的项目有一个依赖 jar,其中包含(在 jar 中)@WebFilter映射到"/*".
我需要jar(它有很多我公司的公共类),但是这个新项目不需要这个WebFilter,实际上这个新项目不会工作,因为这个过滤器检查用户身份验证并且新项目没有“loggedUser”。就像一个网站

谢谢

4

2 回答 2

9

web.xml正是出于这个原因,它优先于注释。只需以web.xml旧的方式声明有问题的过滤器并将其设置<filter-mapping>为虚假的,例如:

<filter>
    <filter-name>BadBadFilter</filter-name>
    <filter-class>com.example.BadBadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>BadBadFilter</filter-name>
    <url-pattern>/this-path-does-not-exist/*</url-pattern>
</filter-mapping>

这将有效地禁用它。

于 2013-09-09T19:00:50.633 回答
0

如果您使用的是 Spring Boot,@WebFilter 可以由 Spring Boot Server 自动实例化,而无需依赖 Beans 定义。我发现解决问题的方法是在嵌入式 Tomcat 服务器识别 @WebFilter 之前在 Spring Boot 中注册我自己的过滤器。这样,@WebFilter 之前已经注册,并且嵌入式服务器不会覆盖您的。

为了实现这一点,您需要在服务器找到过滤器之前对其进行注册。我确实注册了我的过滤器并进行了如下更改:

/**
 * Creates the Bean. Observe that @WebFilter is not registered as a Bean.
 */
@Bean
public SomeFilter someFilter() {
    return new SomeFilter();
}

其次,您需要使用相同的名称进行注册。找到服务器用于注册过滤器的名称很重要。通常,如果 @WebFilter 标记没有提供,它将是您的类的完整名称

/**
 * It is important to keep the same name; when Apache Catalina tries to automatically register the filter,
 * it will check that is has already been registered.
 * @param filter SomeFilter
 * @return
 */
@Bean
public FilterRegistrationBean registration(SomeFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean(filter);
    registration.setEnabled(true);
    registration.setAsyncSupported(true);
    registration.setName("some.class.path.for.some.filter.SomeFilter");
    registration.setUrlPatterns(Lists.<String>newArrayList("/some-url-does-not-exist/*"));
    return registration;
}

在我的场景中,我必须启用 async=true,所以我也添加了该行。

于 2018-10-04T01:52:46.160 回答