据说我们可以使用@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"));
}
我们如何才能实现这一目标?