Listener是在servlet2.3中加入的,主要用于對Session,request,context等進行監(jiān)控。使用Listener需要實現(xiàn)響應(yīng)的接口。觸發(fā)Listener事件的時候,tomcat會自動調(diào)用Listener的方法。在web.xml中配置標(biāo)簽,一般要配置在標(biāo)簽前面,可配置多個,同一種類型也可配置多個com.xxx.xxx.ImplementListenerservlet2.5的規(guī)范中共有8中Listener,分別監(jiān)聽session,context,request等的創(chuàng)建和銷毀,屬性變化等。
常用的監(jiān)聽接口: 監(jiān)聽對象HttpSessionListener :監(jiān)聽HttpSession的操作,監(jiān)聽session的創(chuàng)建和銷毀。 可用于收集在線著信息ServletRequestListener:監(jiān)聽request的創(chuàng)建和銷毀。ServletContextListener:監(jiān)聽context的創(chuàng)建和銷毀。??
啟動時獲取web.xml里配置的初始化參數(shù)監(jiān)聽對象的屬性HttpSessionAttributeListener :ServletContextAttributeListener :ServletRequestAttributeListener :監(jiān)聽session內(nèi)的對象HttpSessionBindingListener:對象被放到session里執(zhí)行valueBound(),對象移除時執(zhí)行valueUnbound()。對象必須實現(xiàn)該lisener接口。HttpSessionActivationListener:服務(wù)器關(guān)閉時,會將session里的內(nèi)容保存到硬盤上,這個過程叫做鈍化。服務(wù)器重啟時,會將session內(nèi)容從硬盤上重新加載。
下面為大家分享一個Listener的應(yīng)用實例:利用HttpSessionListener統(tǒng)計最多在線用戶人數(shù)
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) {? ? ? ? ? ? //記錄最多人數(shù)是多少? ? ? ? ? ? app.setAttribute("maxOnLineCount", count);? ? ? ? ? ? DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");? ? ? ? ? ? //記錄在那個時刻達到上限? ? ? ? ? ? app.setAttribute("date", df.format(new Date()));? ? ? ? }? ? }? ? //session注銷、超時時候調(diào)用,停止tomcat不會調(diào)用? ? public void sessionDestroyed(HttpSessionEvent event) {? ? ? ? ServletContext app = event.getSession().getServletContext();? ? ? ? int count = Integer.parseInt(app.getAttribute("onLineCount").toString());? ? ? ? count--;? ? ? ? app.setAttribute("onLineCount", count);? ? ? ? }
}