實現 ServletContextListener 接口,並複寫 contextDestroyed() 、contextInitialized() 。java
web.xml 中註冊這個監聽器。web
ServletListener.javaapp
package test; 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.xmlide
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app version="2.5" 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_2_5.xsd"> <listener> <listener-class>test.ServletListener</listener-class> </listener> </web-app>