Is there a way to run a method/class only on Tomcat/Wildfly/Glassfish startup?

dcave555 picture dcave555 · Oct 1, 2008 · Viewed 40.1k times · Source

I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml.

Is there a way to run a method/class only on Tomcat startup?

Answer

skaffman picture skaffman · Oct 1, 2008

You could write a ServletContextListener which calls your method from the contextInitialized() method. You attach the listener to your webapp in web.xml, e.g.

<listener>
   <listener-class>my.Listener</listener-class>
</listener>

and

package my;

public class Listener implements javax.servlet.ServletContextListener {

   public void contextInitialized(ServletContext context) {
      MyOtherClass.callMe();
   }
}

Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing.