因为项目一些代码原因,tomcat老僵死,linux下执行tomcat的shutdown脚本总是无法关闭。考虑到改代码逻辑不太实际,于是写了个监听器类实现ServletContextListener,在contextDestroyed方法中实现关闭的逻辑,再在web.xml配好,问题搞定。
由于之前没怎么用过这个,有点好奇。趁有空做了个简单的测试。
测试A:
public class TestListener implements ServletContextListener{
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("111111111111111111111111111111111111 ddddddddddddddddddddddddddddddd");
}
public void contextInitialized(ServletContextEvent sce) {
System.out.println("111111111111111111111111111111111111");
}
}
测试B:
public class ServletDestroyListener implements ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("2222222222222222222222222222222222222222222 ddddddddddddddddddddddd");
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("2222222222222222222222222222222222222222222");
}
}
web.xml配置先后:
<listener>
<listener-class>com.xxx.listener.TestListener</listener-class>
</listener>
<listener>
<listener-class>com.xxx.listener.ServletDestroyListener</listener-class>
</listener>
开启时:
111111111111111111111111111111111111
2222222222222222222222222222222222222222222
关闭时:
2222222222222222222222222222222222222222222 ddddddddddddddddddddddd
111111111111111111111111111111111111 ddddddddddddddddddddddddddddddd
得出以下结论:
多个ServletContextListener可以一起使用。
contextInitialized方法按照web.xml的配置顺序执行。
contextDestroyed方法按照web.xml的配置逆序执行。
类似拦截器。
PS:值得一提的是,如果listener需要在其他工具载入完或者销毁前执行,请将listener放在它之后。比如spring的ContextLoaderListener。