How can I add a servlet filter programmatically?

后端 未结 1 1987
野的像风
野的像风 2020-12-30 07:12

Although I\'ve seen many similar questions, I didn\'t find a clear answer. Using Servlet Spec 2.5, is it possible to add servlet filters and mappings programmatically? The p

相关标签:
1条回答
  • 2020-12-30 07:26

    No, not by the standard Servlet 2.5 API. This was introduced in Servlet 3.0. Your best bet is to create a single filter and reinvent the chain of responsibility pattern yourself. An alternative is to grab container specific classes from under the covers and then add the filter by its API. How exactly to do that depends on the target container (and it would also make your code tight coupled to the container in question).

    See also:

    • How to add filters to servlet without modifying web.xml

    Update: as requested by comment, here's an example in flavor of a ServletContextListener how you could add filters programmatically during webapp's startup using Tomcat 6 specific APIs:

    package com.example;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    import org.apache.catalina.Container;
    import org.apache.catalina.ServerFactory;
    import org.apache.catalina.core.StandardContext;
    import org.apache.catalina.core.StandardEngine;
    import org.apache.catalina.deploy.FilterDef;
    import org.apache.catalina.deploy.FilterMap;
    
    public class Tomcat6FilterConfigurator implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            StandardEngine engine = (StandardEngine) ServerFactory.getServer().findService("Catalina").getContainer();
            Container container = engine.findChild(engine.getDefaultHost());
            StandardContext context = (StandardContext) container.findChild(event.getServletContext().getContextPath());
    
            FilterDef filter1definition = new FilterDef();
            filter1definition.setFilterName(Filter1.class.getSimpleName());
            filter1definition.setFilterClass(Filter1.class.getName());
            context.addFilterDef(filter1definition);
    
            FilterMap filter1mapping = new FilterMap();
            filter1mapping.setFilterName(Filter1.class.getSimpleName());
            filter1mapping.addURLPattern("/*");
            context.addFilterMap(filter1mapping);
    
            // ...
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            // TODO Auto-generated method stub
    
        }
    
    }
    

    Register this listener as follows in web.xml:

    <listener>
        <listener-class>com.example.Tomcat6FilterConfigurator</listener-class>
    </listener>
    

    Once again, keep in mind that this does not work on containers of other make/version, even not on Tomcat 7.0.

    0 讨论(0)
提交回复
热议问题