监听Web容器启动与关闭
1.在Servlet API 中有一个 ServletContextListener 接口,它能够监听 ServletContext 对象的生命周期;
实际上就是监听 Web 应用的生命周期。
要监听web容器的启动与关闭,首先定义一个类继承ServletContextListener 接口:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* web容器监听
* @author Administrator
*
*/
public class WebListener implements ServletContextListener{
/**
* web容器关闭调用
*/
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("web容器关闭调用");
}
/**
* web容器开启调用
*/
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("web容器开启调用");
}
}
2.然后在web.xml中注册该类的监听器:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 添加监听器 -->
<listener >
<listener-class>com.WebListener</listener-class>
</listener>
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>