// Three steps to use a listener
// Step 1. Implement a listener interface
// Step 2. Write its callable methods
// Step 3. Register in the web.xml
when the ServletContext object is created, it has public void contextInitialized(ServletContextEvent sce)
when the ServletContext object is destroyed, is has public void contextDestroyed(ServletContextEvent sce)
// here is MyServletContextlistenerImpl.java
package com.truman.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListenerImpl implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("The ServletContext object has been created.");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("The ServletContext object has been destroyed.");
}
}
here is registration in web.xml
<listener>
<listener-class>com.truman.listener.MyServletContextListenerImpl</listener-class>
</listener>
here is the output:
deployed, please wait...
21-Jun-2020 09:39:48.426 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.tomcat.util.descriptor.web.WebXml.setVersion Unknown version string [4.0]. Default version will be used.
The ServletContext object has been created. // this line
[2020-06-21 09:39:48,598] Artifact thirdTry:war exploded: Artifact is deployed successfully
//*************************************************************************************************
21-Jun-2020 09:39:57.924 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/Users/zhuya/apache-tomcat-8.5.38/webapps/manager] has finished in [42] ms
The ServletContext object has been destroyed. // and this line
21-Jun-2020 09:39:57.938 INFO [main] org.apache.coyote.AbstractProtocol.stop Stopping ProtocolHandler ["http-nio-8080"]
原文:https://www.cnblogs.com/nedrain/p/13171464.html