ServletContainerInitializer 中 contextDestroyed() 的等价物是什么?
what is the equivalence of contextDestroyed() in ServletContainerInitializer?
我必须创建一个实现 ServletContextListener
to add an event during the initialization or the shutdown of Tomcat. However, the class has to be located in a jar file inside WEB-INF/lib
. After doing some readings, I found out that this is not possible, and the alternative is to use ServletContainerInitializer
的 class。但是,只有 onStartup()
方法可用。
是否有任何其他替代方法可以让我在 Web 应用程序关闭或销毁期间添加事件?
我正在使用 Tomcat 8 和 Java 8 顺便说一句。
不确定您是如何测试代码的。但是这个 ServletContextListener 在 Tomcat 8.5.5 上对我来说工作正常。试试这个代码,不需要把它放到单独的 JAR 文件中。
@WebListener
public class AppContextListener implements ServletContextListener{
Logger log = LoggerFactory.getLogger(AppContextListener.class);
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
log.info("### Context is destroyed ###");
}
}
让您的 ServletContainerInitializer
以编程方式添加一个 ServletContextListener
,后者又会在其 contextDestroyed()
.
中完成所需的工作
servletContext.addListener(YourServletContextListener.class);
我必须创建一个实现 ServletContextListener
to add an event during the initialization or the shutdown of Tomcat. However, the class has to be located in a jar file inside WEB-INF/lib
. After doing some readings, I found out that this is not possible, and the alternative is to use ServletContainerInitializer
的 class。但是,只有 onStartup()
方法可用。
是否有任何其他替代方法可以让我在 Web 应用程序关闭或销毁期间添加事件?
我正在使用 Tomcat 8 和 Java 8 顺便说一句。
不确定您是如何测试代码的。但是这个 ServletContextListener 在 Tomcat 8.5.5 上对我来说工作正常。试试这个代码,不需要把它放到单独的 JAR 文件中。
@WebListener
public class AppContextListener implements ServletContextListener{
Logger log = LoggerFactory.getLogger(AppContextListener.class);
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
log.info("### Context is destroyed ###");
}
}
让您的 ServletContainerInitializer
以编程方式添加一个 ServletContextListener
,后者又会在其 contextDestroyed()
.
servletContext.addListener(YourServletContextListener.class);