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

后端 未结 3 1037
遥遥无期
遥遥无期 2020-11-29 20:50

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

相关标签:
3条回答
  • 2020-11-29 21:26

    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:

    <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> 
    
    0 讨论(0)
  • 2020-11-29 21:28

    You can also use (starting Servlet v3) an 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) {
    
            }
        }
    
    0 讨论(0)
  • 2020-11-29 21:35

    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.

    0 讨论(0)
提交回复
热议问题