實現session監聽器

監聽器概述   
  
1.Listener是Servlet的監聽器    
2.能夠監聽客戶端的請求、服務端的操做等。   
3.經過監聽器,能夠自動激發一些操做,如監聽在線用戶數量,當增長一個HttpSession時,給在線人數加1。   
4.編寫監聽器須要實現相應的接口   
5.編寫完成後在web.xml文件中配置一下,就能夠起做用了   
6.能夠在不修改現有系統基礎上,增長web應用程序生命週期事件的跟蹤   
  
  
經常使用的監聽接口   
  
java

Java代碼  收藏代碼web

  1. 1.ServletContextAttributeListener     數據庫

  2. 監聽對ServletContext屬性的操做,好比增長/刪除/修改     服務器

  3. 2.ServletContextListener     session

  4. 監聽ServletContext,當建立ServletContext時,激發 contextInitialized(ServletContextEvent sce)方法;當銷燬ServletContext時,激發contextDestroyed(ServletContextEvent sce)方法。     app

  5. 3.HttpSessionListener     this

  6. 監聽HttpSession的操做。當建立一個 Session時,激發session Created(SessionEvent se)方法;當銷燬一個Session時,激發sessionDestroyed (HttpSessionEvent se)方法。     spa

  7. 4.HttpSessionAttributeListener     code

  8. 監聽HttpSession中的屬性的操做。當在Session增長一個屬性時,激發 attributeAdded(HttpSessionBindingEvent se) 方法;當在Session刪除一個屬性時,激發attributeRemoved(HttpSessionBindingEvent se)方法;當在Session屬性被從新設置時,激發attributeReplaced(HttpSessionBindingEvent se) 方法。    server


  
使用範例:   
由監聽器管理共享數據庫鏈接   
  
生命週期事件的一個實際應用由context監聽器管理共享數據庫鏈接。在web.xml中以下定義監聽器:   

Java代碼  收藏代碼 

  1. <listener>     
        <listener-class>XXX.MyConnectionManager</listener-class>     
    </listener>


server建立監聽器的實例,接受事件並自動判斷實現監聽器接口的類型。要記住的是因爲監聽器是配置在部署描述符web.xml中,因此不須要改變任何代碼就能夠添加新的監聽器。   

Java代碼  收藏代碼

  1.     
    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關閉的時候隨之關閉。     
  
在web.xml中加入:   

Java代碼  收藏代碼

  1. <listener>
    <listener-class>servletlistener111111.SecondListener</listener-class> 
    </listener>



================================================== 

關於用戶超時的例子: 

Java代碼  收藏代碼

  1. public class OnlineUserListener implements HttpSessionListener {  
        public void sessionCreated(HttpSessionEvent event) {  
        }  
        public void sessionDestroyed(HttpSessionEvent event) {  
            HttpSession session = event.getSession();  
            ServletContext application = session.getServletContext();  
            // 取得登陸的用戶名  
            String username = (String) session.getAttribute("username");  
            // 從在線列表中刪除用戶名  
            List onlineUserList = (List) application.getAttribute("onlineUserList");  
            onlineUserList.remove(username);  
            System.out.println(username + "超時退出。");  
        }  
    }



如下兩種狀況下就會發生sessionDestoryed(會話銷燬)事件: 

1.執行session.invalidate()方法時。例如:request.getSession().invalidate(); 

2.若是用戶長時間沒有訪問服務器,超過了會話最大超時時間,服務器就會自動銷燬超時的session。會話超時時間能夠在web.xml中進行設置。 

======================================== 

使用HttpSessionBindingListener 

HttpSessionBindingListener雖然叫作監聽器,但使用方法與HttpSessionListener徹底不一樣。咱們實際看一下它是如何使用的。 

咱們的OnlineUserBindingListener實現了HttpSessionBindingListener接口,接口中共定義了兩個方法:valueBound()和valueUnbound(),分別對應數據綁定,和取消綁定兩個事件。 

所謂對session進行數據綁定,就是調用session.setAttribute()把HttpSessionBindingListener保存進session中。咱們在LoginServlet.java中進行這一步。 

// 把用戶名放入在線列表 
session.setAttribute("onlineUserBindingListener", new OnlineUserBindingListener(username)); 
       
這就是HttpSessionBindingListener和HttpSessionListener之間的最大區別:HttpSessionListener只須要設置到web.xml中就能夠監聽整個應用中的全部session。 HttpSessionBindingListener必須實例化後放入某一個session中,才能夠進行監聽。 

從監聽範圍上比較,HttpSessionListener設置一次就能夠監聽全部session,HttpSessionBindingListener一般都是一對一的。 

正是這種區別成就了HttpSessionBindingListener的優點,咱們可讓每一個listener對應一個username,這樣就不須要每次再去session中讀取username,進一步能夠將全部操做在線列表的代碼都移入listener,更容易維護。 

valueBound()方法的代碼以下: 

Java代碼  收藏代碼

public void valueBound(HttpSessionBindingEvent event) {  
    HttpSession session = event.getSession();  
    ServletContext application = session.getServletContext();  
  
    // 把用戶名放入在線列表  
    List onlineUserList = (List) application.getAttribute("onlineUserList");  
    // 第一次使用前,須要初始化  
    if (onlineUserList == null) {  
        onlineUserList = new ArrayList();  
        application.setAttribute("onlineUserList", onlineUserList);  
    }  
    onlineUserList.add(this.username);  
}
           
    username已經經過構造方法傳遞給listener,在數據綁定時,能夠直接把它放入用戶列表。 

    與之對應的valueUnbound()方法,代碼以下: 

Java代碼  收藏代碼

public void valueUnbound(HttpSessionBindingEvent event) {  
    HttpSession session = event.getSession();  
    ServletContext application = session.getServletContext();  
  
    // 從在線列表中刪除用戶名  
    List onlineUserList = (List) application.getAttribute("onlineUserList");  
    onlineUserList.remove(this.username);  
  
    System.out.println(this.username + "退出。");  
}
           
    這裏能夠直接使用listener的username操做在線列表,沒必要再去擔憂session中是否存在username。 

    valueUnbound的觸發條件是如下三種狀況: 

Java代碼  收藏代碼

  1. 1.執行session.invalidate()時。  

  2.   

  3. 2.session超時,自動銷燬時。  

  4.   

  5. 3.執行session.setAttribute("onlineUserListener""其餘對象");或session.removeAttribute("onlineUserListener");將listener從session中刪除時。  



所以,只要不將listener從session中刪除,就能夠監聽到session的銷燬。

相關文章
相關標籤/搜索