一、创建监听器步骤说明
- 自定义监听器类
- 实现监听器接口 重写接口中的方法
- 在web.xml文件中,对监听器进行注册
二、具体代码
- 自定义监听器类并实现监听器接口 重写接口中的方法
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("****************ServletContext 对象销毁了****************");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("****************ServletContext 对象创建了****************");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 在web.xml文件中,对监听器进行注册
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>day_20220909display-name>
<listener>
<listener-class>com.heima.MyServletContextListenerlistener-class>
listener>
web-app>
- 启动服务,即会创建servletContext对象
信息: Initializing ProtocolHandler ["http-apr-8080"]
九月 09, 2022 4:02:11 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["ajp-apr-8009"]
九月 09, 2022 4:02:11 下午 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1533 ms
九月 09, 2022 4:02:11 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service Catalina
九月 09, 2022 4:02:11 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.0.53
九月 09, 2022 4:02:12 下午 org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
警告: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [405] milliseconds.
****************ServletContext 对象创建了****************
九月 09, 2022 4:02:12 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-apr-8080"]
九月 09, 2022 4:02:12 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["ajp-apr-8009"]
九月 09, 2022 4:02:12 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 812 ms

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18