ServletContextListener監聽ServletContext一生中兩個關鍵的事件——創建和撤銷
下面的實例是通過監聽器獲取初始化參數,並創建一個Dog對象,存放在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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<context-param>
<param-name>dogName</param-name>
<param-value>TomEgg</param-value>
</context-param>
<listener>
<listener-class>com.zhongqian.listener.TestServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.zhongqian.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
②創建TestServletContextListener和TestServlet。
public class TestServletContextListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("get into testServletContextListener contextDestoryed method.");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("get into testServletContextListener's contextInitialized method.");
ServletContext sc = arg0.getServletContext();
String dogName = sc.getInitParameter("dogName");
Dog d = new Dog(dogName);
sc.setAttribute("dog", d);
}
}
public class TestServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Dog d = (Dog)this.getServletContext().getAttribute("dog");
System.out.println(d.getDogName());
}
}
③創建Dog類
服務器啓動時,即調用了監聽器。當客戶端訪問testServlet.do時,在控制檯打印TomEgg.
除了上下文監聽器外,還有很多其他的監聽器。常見的8個監聽器如下:
注意:監聽器的初始化是在服務器啓動時完成的。因此可以在監聽器中完成一些初始化工作。如:spring框架就是通過監聽器完成初始化工作,讀取配置文件,完成注入。