How to catch tomcat close event?

I want to start the thread every time the tomcat server starts. To do this, I need to catch the tomcat close event. How can i do this? I tried to do this using sessions, but sometimes the session even persists after closing and repeating tomcat? What are my options?

+4
source share
1 answer

You can try to catch the JVM shutdown event as follows:

    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            System.out.println("BYE BYE");
        }
    });

Another option is to implement ServletContextListener using @WebListener Annotation. In this case, no xml configuration is required.

@WebListener
public class MyLifeCycleListener implements ServletContextListener {

      public void contextInitialized(ServletContextEvent event) {
          //TODO ON START
      }

      public void contextDestroyed(ServletContextEvent event) {
          //TODO ON DESTROY
      }
}
+4
source

Source: https://habr.com/ru/post/1548657/


All Articles