Servlet 監聽器應用(轉)
監聽器概述
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>
怎么樣,就是這么簡單,不用對現有代碼做任何的修改。
posted on 2007-12-03 16:51 都市淘沙者 閱讀(830) 評論(0) 編輯 收藏 所屬分類: JSP/PHP