Is there a way to run a method / class only when starting Tomcat / Wildfly / Glassfish?

I need to delete temporary files when Tomcat starts, the transition to the folder containing the temporary files is in applicationContext.xml.

Is there a way to run a method / class only when Tomcat starts?

+42
java java-ee web-applications tomcat startup
01 Oct '08 at 15:55
source share
3 answers

You can write a ServletContextListener that calls your method from the contextInitialized() method. For example, you attach a listener to webapp in web.xml, for example.

 <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 only starts once when webapp starts, and not when Tomcat starts, but it can mean the same thing.

+68
Oct 01 '08 at 16:01
source share

You can also use (starting servlet v3) annotated aproach (no need to add anything to web.xml):

  @WebListener public class InitializeListner implements ServletContextListener { @Override public final void contextInitialized(final ServletContextEvent sce) { } @Override public final void contextDestroyed(final ServletContextEvent sce) { } } 
+8
Oct 25 '14 at
source share

I'm sure there should be a better way to do this as part of the container's life cycle (edit: Hank has an answer - I was wondering why he suggested SessonListener before I answered), but you could create a servlet that has no other purpose , except for performing one-time actions at server startup:

 <servlet> <description>Does stuff on container startup</description> <display-name>StartupServlet</display-name> <servlet-name>StartupServlet</servlet-name> <servlet-class>com.foo.bar.servlets.StartupServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> 
+3
Oct 01 '08 at 16:08
source share



All Articles