ServletContextListener作用是在servlet容器启动和关闭会执行一系列操作,有时我们需要在容器启动后自动执行一系统操作,我们就需要使用ServletContextListener。
一、使用ServletContextListener
1, 要先实现 ServletContextListener 接口,并复写 contextDestroyed() 、contextInitialized() 。contextInitialized()表示容器启动时启动完成后执行的内容。
contextDestroyed()表示器容关闭时将要关闭前执行的内容。
2, 在web应用程序中的web.xml中配置监听
<listener>
<listener-class>com.xxx.test.ServletListener</listener-class>
</listener>
二、使用例子
package com.xxx.tecst;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ServletListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContext容器销毁时调用!");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContext容器启动时调用!");
}
}
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="schedule-console" version="3.0">
<listener>
<listener-class>com.xxx.test.ServletListener</listener-class>
</listener>
</web-app>