監聽器概述
1.Listener是Servlet的監聽器
2.可以監聽用戶端的請求、服務端的操作等。
3.通過監聽器,可以自動激發一些操作,如監聽線上使用者數量,當增加一個HttpSession時,給線上人數加1。
4.編寫監聽器需要實現相應的介面
5.編寫完成後在web.xml檔案中配置一下,就可以起作用了
6.可以在不修改現有系統基礎上,增加web應用程式生命週期事件的跟蹤
常用的監聽介面
1.ServletContextAttributeListener
監聽對ServletContext屬性的操作,比如增加/刪除/修改
2.ServletContextListener
監聽ServletContext,當建立ServletContext時,激發contextInitialized(ServletContextEvent sce)方法;當銷毀ServletContext時,激發contextDestroyed(ServletContextEvent sce)方法。
3.HttpSessionListener
監聽HttpSession的操作。當建立一個Session時,激發session Created(SessionEvent se)方法;當銷毀一個Session時,激發sessionDestroyed (HttpSessionEvent se)方法。
4.HttpSessionAttributeListener
監聽HttpSession中的屬性的操作。當在Session增加一個屬性時,激發attributeAdded(HttpSessionBindingEvent se) 方法;當在Session刪除一個屬性時,激發attributeRemoved(HttpSessionBindingEvent se)方法;當在Session屬性被重新設定時,激發attributeReplaced(HttpSessionBindingEvent se) 方法。
使用範例:
由監聽器管理共用資料庫串連
生命週期事件的一個實際應用由context監聽器管理共用資料庫串連。在web.xml中如下定義監聽器:
<listener>
<listener-class>XXX.MyConnectionManager</listener-class>
</listener> Øserver建立監聽器的執行個體,接受事件並自動判斷實現監聽器介面的類型。要記住的是由於監聽器是配置在部署描述符web.xml中,所以不需要改變任何代碼就可以添加新的監聽器。
public class MyConnectionManager implements ServletContextListener{
public void contextInitialized(ServletContextEvent e) {
Connection con = // create connection
e.getServletContext().setAttribute("con", con);
}
public void contextDestroyed(ServletContextEvent e) {
Connection con = (Connection) e.getServletContext().getAttribute("con");
try {
con.close();
}
catch (SQLException ignored) { } // close connection
}
}
監聽器保證每新產生一個servlet context都會有一個可用的資料庫連接,並且所有的串連對會在context關閉的時候隨之關閉。
計算線上使用者數量的Linstener
(1)
Package xxx;
public class OnlineCounter {
private static long online = 0;
public static long getOnline(){
return online;
}
public static void raise(){
online++;
}
public static void reduce(){
online--;
}
}
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineCounterListener implements HttpSessionListener{
public void sessionCreated(HttpSessionEvent hse) {
OnlineCounter.raise();
}
public void sessionDestroyed(HttpSessionEvent hse){
OnlineCounter.reduce();
}
}
在需要顯示線上人數的JSP中可是使用
目前線上人數:
<%@ page import=“xxx.OnlineCounter" %>
<%=OnlineCounter.getOnline()%>
退出會話(可以給使用者提供一個登出按鈕):
<form action="exit.jsp" method=post>
<input type=submit value="exit">
</form>
exit.jsp: <%session.invalidate() ;%>
在web.xml中加入:
<listener>
<listener-class>servletlistener111111.SecondListener</listener-class> </listener>
怎麼樣,就是這麼簡單,不用對現有代碼做任何的修改。