如何捕捉关闭tomcat的事件?

我想要的是每次tomcat服务器启动时启动一个线程。为此我需要捕获关闭tomcat的事件。我可以这样做吗?我试着用会话来做但有时会话会在关闭后继续下来并重申tomcat?我的选择是什么?

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

  Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("BYE BYE"); } }); 

另一个选项是使用@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 } }