一 .監聽器(Listener)
監聽器(Listener)可以監聽客戶端的請求、服務器端的操作。通過監聽器可以自動觸發一些事件,比如監聽在線的用戶數量。監聽器對象可以在事件發生前、發生後做一些必要的處理。
Listener接口和Event類
在web.xml中配置監聽器的格式如下:
<listener>
<listener-class>監聽類</listener-class>
</listener>
在3.0以後 一般直接用註解即可
@WebListener
1.監聽ServletContextListener的實例代碼
/**
* ServletContextListener接口用於監聽Servlet上下文的變化
* 其兩個方法被稱爲“Web應用程序的生命週期方法”。在這兩個方法中,
* 都需要一個ServletContextEvent類型的參數,該類只有以下一個方法。
* ■ ServletContext getServletContext():獲得ServletContext對象。
*/
@WebListener
public class MyContextListener implements ServletContextListener{
public MyContextListener() {
}
/**
* 上下文初始化
* 當ServletContext對象創建的時候,將會調用此方法進行處理。
*
* @param sce
*/
public void contextInitialized(ServletContextEvent sce) {
logout("contextInitialized()-->ServletContext初始化了");
}
/**
* 上下文銷燬
* 當ServletContext對象銷燬的時候(例如關閉Web容器或者重新加載應用),將會調用此方法進行處理。
*
* @param arg0
*/
public void contextDestroyed(ServletContextEvent arg0) {
logout("contextDestroyed()-->ServletContext被銷燬");
}
}
2.ServletAttributeListener接口
/**
*ServletAttributeListener接口用於監聽ServletContext中屬性的變化,
* 該接口提供3個方法,分別用於處理ServletContext中屬性的增加、刪除和修改。
*/
@WebListener
public class MyContextListener implements ServletContextAttributeListener {
public MyContextListener() {
}
/**
* 添加屬性
* 當ServletContext中增加一個屬性時,將會調用此方法進行處理。
* @param scae
*/
public void attributeAdded(ServletContextAttributeEvent scae) {
logout("增加了一個ServletContext屬性:attributeAdded('" +
scae.getName()+ "', '" + scae.getValue() + "')");
}
/**
* 修改屬性
* 當ServletContext中修改一個屬性值時,將會調用此方法進行處理。
* @param scae
*/
public void attributeReplaced(ServletContextAttributeEvent scae) {
logout("某個ServletContext的屬性被改變:attributeReplaced ('"
+scae.getName()+ "', '" + scae.getValue() + "')");
}
/**
* 移除屬性
*當ServletContext中刪除一個屬性時,將會調用此方法進行處理。
* @param scae
*/
public void attributeRemoved(ServletContextAttributeEvent scae) {
logout("刪除了一個ServletContext屬性:attributeRemoved ('"
+scae.getName()+ "', '" + scae.getValue() + "')");
}
// 寫日誌信息
private void logout(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileOutputStream("C:\\log.txt",
true));
SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String curtime = datef.format(new Date());
out.println(curtime + "::Form ContextListener: " + message);
out.close();
} catch (Exception e) {
out.close();
e.printStackTrace();
}
}
}
在應用中,如果監聽類同時實現ServletContextListener和ServletContextAttributeListener兩個接口,其工作流程如下:
01 Web應用啓動的時候,contextInitialized(ServletContextEvent event)方法進行初始化。
02 如果在Application範圍內添加一個屬性,將會觸發ServletContextAttributeEvent事件,通過AttributeAdded(ServletContextAttributeEvent event)方法進行處理。
03 如果在Application的範圍內修改屬性值,將會觸發ServletContextAttributeEvent事件,通過AttributeReplaced(ServletContextAttributeEvent event)方法進行處理。
04 如果在Application的範圍內刪除一個屬性,將會觸發ServletContextAttributeEvent事件,通過AttributeRemoved(ServletContextAttributeEvent event)方法進行處理。
05 Web應用關閉時,contextDestroyed(ServletContextEvent event)方法進行卸載。
上下文監聽器的工作流程如圖所示。
注意在實際應用中,自定義的類可以實現ServletContextListener和ServletContextAttributeListener其中之一,從而完成特定的應用。