Listener實在servlet2.3中加入的,主要用於對Session,request,context等進行監控。
使用Listener需要實現響應的接口。觸發Listener事件的時候,tomcat會自動調用Listener的方法。
在web.xml中配置標籤,一般要配置在<servlet>標籤前面,可配置多個,同一種類型也可配置多個
<listener>
<listener-class>com.xxx.xxx.ImplementListener</listener-class>
</listener>
servlet2.5的規範中共有8中Listener,分別監聽session,context,request等的創建和銷燬,屬性變化等。
常用的監聽接口:
監聽對象
HttpSessionListener :監聽HttpSession的操作,監聽session的創建和銷燬。 可用於收集在線着信息
ServletRequestListener:監聽request的創建和銷燬。
ServletContextListener:監聽context的創建和銷燬。 啓動時獲取web.xml裏配置的初始化參數
監聽對象的屬性
HttpSessionAttributeListener :
ServletContextAttributeListener :
ServletRequestAttributeListener :
監聽session內的對象
HttpSessionBindingListener:對象被放到session裏執行valueBound(),對象移除時執行valueUnbound()。對象必須實現該lisener接口。
HttpSessionActivationListener:服務器關閉時,會將session裏的內容保存到硬盤上,這個過程叫做鈍化。服務器重啓時,會將session內容從硬盤上重新加載。
Listener應用實例
利用HttpSessionListener統計最多在線用戶人數
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class HttpSessionListenerImpl implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { ServletContext app = event.getSession().getServletContext(); int count = Integer.parseInt(app.getAttribute("onLineCount").toString()); count++; app.setAttribute("onLineCount", count); int maxOnLineCount = Integer.parseInt(app.getAttribute("maxOnLineCount").toString()); if (count > maxOnLineCount) { //記錄最多人數是多少 app.setAttribute("maxOnLineCount", count); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //記錄在那個時刻達到上限 app.setAttribute("date", df.format(new Date())); } } //session註銷、超時時候調用,停止tomcat不會調用 public void sessionDestroyed(HttpSessionEvent event) { ServletContext app = event.getSession().getServletContext(); int count = Integer.parseInt(app.getAttribute("onLineCount").toString()); count--; app.setAttribute("onLineCount", count); } }
參考資料:
http://www.cnblogs.com/hellojava/archive/2012/12/26/2833840.html