views:

40

answers:

2

Can I write a module/filter that gets put into the processing pipleline in Tomcat BEFORE the web application even gets run?

Something that I could turn on/off for each web application that tomcat is handling.

is this possible?

So basically it would be a re-usable filter that hooks into the web pipeline that could alter the requests behavior or perform/modify the requests. One example would be to log all ip's, or redirect based on the url, block the request, etc.

A: 

Have you considered a ServletContextListener in web.xml?

Thorbjørn Ravn Andersen
Is that something that could be hosted externally to a particular webapp? i.e. would the listeners .jar be stored outside of the scope of a web app, so other web apps could use it?
Blankman
It is found through the normal web app classloader, so your question is essentially a deployment issue. Personally I like my WAR's to be self contained. If you want a global configuration file for your WARs then consider an EAR deployment, or a property file in the web container itself.
Thorbjørn Ravn Andersen
+1  A: 

If you are using Servlet 3.0 you can. What you do is implement either a ServletContextListener or a ServletContainerInitializer. The code below shows withServletContextListener

@WebListener("auto config listeners")
public class MyListenerConfigurator implements ServletContextListener {
   public void contextInitialized(ServletContextEvent scEvt) {
      ServletContext ctx = scEvt.getServletContext();
      FilterRegistration.Dynamic reg = ctx.addFilter("myFilter", "my.listener.class.MyListener");
      ...
   }

See EE6 docs here. Perhaps the only drawback is that you can add but you cannot remove. And you can only at when the application starts up.

Note: code not tested

Chuk Lee