Disable @WebFilter (embedded in dependency jar)

▼魔方 西西 提交于 2019-12-05 14:06:30

web.xml takes precedence over annotations for precisely this reason. Simply declare the offending filter in web.xml the good old way and set its <filter-mapping> to something bogus, eg:

<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>

This will effectively disable it.

If you are using Spring Boot, @WebFilter can get automatically instantiated by the Spring Boot Server without relying on Beans definition. The way I found to solve the issue is to register my own filter in the Spring Boot before the @WebFilter is identified by the embedded Tomcat Server. On that way, the @WebFilter is already registered before and the embedded server does not overwrite yours.

In order to achieve that, you need to register the filter before it is found by the server. I did register my filter and made the changes as follows:

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

Secondly, you need to register with the same name. It is important to find the name the server is using to register your filter. Usually, if not provided by the @WebFilter tag, it is going to be the complete name of your class

/**
 * 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;
}

In my scenario, I had to enable async=true, so I have added that line as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!