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().
Although I’ve seen many similar questions, I didn’t find a clear answer. Using Servlet
Share
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
ServletContextListenerhow you could add filters programmatically during webapp’s startup using Tomcat 6 specific APIs:Register this listener as follows in
web.xml:Once again, keep in mind that this does not work on containers of other make/version, even not on Tomcat 7.0.