Spring Boot - 嵌入式Tomcat - @WebListener,由@ServletComponentScan扫描,添加了一个过滤器并获取java.lang.UnsupportedOperationException

时间:2017-06-06 12:13:18

标签: spring spring-boot tomcat8 servlet-3.0

据说我们可以使用@ServletComponentScan添加使用@WebListener@WebFilter注释的标准servlet组件,等等。

在我的情况下,我有@WebListener动态添加过滤器:

@WebListener
public class FilterConfigurerListener implements ServletContextListener{

    @Override
    public void contextInitialized(ServletContextEvent sce) {   
        try{
            ...
            ServletContext sc = sce.getServletContext();
            Dynamic rcf = sc.addFilter("myFilter", MyFilter.class);

addFilter()调用会引发以下异常:

java.lang.UnsupportedOperationException: Section 4.4 of the Servlet 3.0 specification does not permit this method to be called from a ServletContextListener that was not defined in web.xml, a web-fragment.xml file nor annotated with @WebListener
    at org.apache.catalina.core.StandardContext$NoPluggabilityServletContext.addFilter(StandardContext.java:6639)
    at com.whatever.FilterConfigurerListener.contextInitialized(FilterConfigurerListener.java:44)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4743)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5207)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

My Spring Boot App的注释如文档中所述:

@ServletComponentScan(basePackageClasses=FilterConfigurerListener.class)
@SpringBootApplication
public class MySpringBootApplication {

看一下org.apache.catalina.core.StandardContext我可以看到这个实现不允许添加过滤器:

    @Override
    public javax.servlet.FilterRegistration.Dynamic addFilter(
            String filterName, Class<? extends Filter> filterClass) {
        throw new UnsupportedOperationException(
                sm.getString("noPluggabilityServletContext.notAllowed"));
    }

我们如何才能实现这一目标?

0 个答案:

没有答案