如何捕捉关闭tomcat的事件?

coo*_*hny 5 java jsp tomcat

我想要的是每次tomcat服务器启动时都启动一个线程.为此,我需要捕获关闭tomcat的事件.我可以这样做吗?我尝试使用会话来做但有时候会话甚至在关闭后仍然存在下来并重申tomcat?我的选择是什么?

die*_*ter 7

您可以尝试以这种方式捕获JVM关闭事件:

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

        public void run() {
            System.out.println("BYE BYE");
        }
    });
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用@WebListener Annotation 实现ServletContextListener .在这种情况下,不需要xml配置.

@WebListener
public class MyLifeCycleListener implements ServletContextListener {

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

      public void contextDestroyed(ServletContextEvent event) {
          //TODO ON DESTROY
      }
}
Run Code Online (Sandbox Code Playgroud)