How can I add a servlet filter programmatically?

Zeemee picture Zeemee · Oct 26, 2011 · Viewed 19.3k times · Source

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 preferred location would be in a Servlet.init() or in ServletContextListener.contextInitialized().

Answer

BalusC picture BalusC · Oct 26, 2011

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:


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.