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?
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?
You could write a
ServletContextListener
which calls your method from thecontextInitialized()
method. You attach the listener to your webapp in web.xml, e.g.and
Strictly speaking, this is only run once on webapp startup, rather than Tomcat startup, but that may amount to the same thing.
I'm sure there must be a better way to do it as part of the container's lifecycle (edit: Hank has the answer - I was wondering why he was suggesting a
SessonListener
before I answered), but you could create a Servlet which has no other purpose than to perform one-time actions when the server is started:You can also use (starting Servlet v3) an annotated aproach (no need to add anything to web.xml):