用HttpSessionAttributeListener接口實現在線統計

以下是一些不詳細的代碼,主要是說明原理:
捕獲Session事件的意義:
1、    記錄網站的客戶登錄日誌(登錄,退出信息等)
2、    統計在線人數
3、    等等還有很多,呵呵,自己想吧……總之挺重要的。

Session代表客戶的會話過程,客戶登錄時,往Session中傳入一個對象,即可跟蹤客戶的會話。在Servlet中,傳入Session的對象如果是一個實現HttpSessionBindingListener接口的對象(方便起見,此對象稱爲監聽器),則在傳入的時候(即調用HttpSession對象的setAttribute方法的時候)和移去的時候(即調用HttpSession對象的removeAttribute方法的時候或Session Time out的時候)Session對象會自動調用監聽器的valueBound和valueUnbound方法(這是HttpSessionBindingListener接口中的方法)。
由此可知,登錄日誌也就不難實現了。
另外一個問題是,如何統計在線人數,這個問題跟實現登錄日誌稍微有點不同,統計在線人數(及其信息),就是統計現在有多少個Session實例存在,我們可以增加一個計數器(如果想存儲更多的信息,可以用一個對象來做計數器,隨後給出的實例中,簡單起見,用一個整數變量作爲計數器),通過在valueBound方法中給計數器加1,valueUnbound方法中計數器減1,即可實現在線人數的統計。當然,這裏面要利用到ServletContext的全局特性。(有關ServletContext的敘述請參考Servlet規範),新建一個監聽器,並將其實例存入ServletContext的屬性中,以保證此監聽器實例的唯一性,當客戶登錄時,先判斷ServletContext的這個屬性是否爲空,如果不爲空,證明已經創建,直接將此屬性取出放入Session中,計數器加1;如果爲空則創建一個新的監聽器,並存入ServletContext的屬性中。

舉例說明:

實現一個監聽器:
// SessionListener.java

import java.io.*;
import java.util.*;
import javax.servlet.http.*;

//監聽登錄的整個過程
public class SessionListener implements HttpSessionBindingListener
{

public String privateInfo="";        //生成監聽器的初始化參數字符串
private String logString="";        //日誌記錄字符串
private int count=0;        //登錄人數計數器

public SessionListener(String info){
   this.privateInfo=info;
}

public int getCount(){
   return count;
}

public void valueBound(HttpSessionBindingEvent event)
{
   count++;
   if (privateInfo.equals("count"))
   {
       return;
   }
   try{
Calendar calendar=new GregorianCalendar();
System.out.println("LOGIN:"+privateInfo+" TIME:"+calendar.getTime());
logString="\nLOGIN:"+privateInfo+" TIME:"+calendar.getTime()+"\n";
for(int i=1;i<1000;i++){
 File file=new File("yeeyoo.log"+i);
 if(!(file.exists()))
   file.createNewFile();   //如果文件不存在,創建此文件
 if(file.length()>1048576) //如果文件大於1M,重新創建一個文件
   continue;
   FileOutputStream foo=new FileOutputStream("yeeyoo.log"+i,true);//以append方式打開創建文件
   foo.write(logString.getBytes(),0,logString.length()); //寫入日誌字符串
   foo.close();
   break;//退出
}
   }catch(FileNotFoundException e){}
    catch(IOException e){}
}

public void valueUnbound(HttpSessionBindingEvent event)
{
   count--;
   if (privateInfo.equals("count"))
   {
       return;
   }
   try{
Calendar calendar=new GregorianCalendar();
System.out.println("LOGOUT:"+privateInfo+" TIME:"+calendar.getTime());
logString="\nLOGOUT:"+privateInfo+" TIME:"+calendar.getTime()+"\n";
for(int i=1;i<1000;i++){
 File file=new File("yeeyoo.log"+i);
 if(!(file.exists()))
   file.createNewFile();   //如果文件不存在,創建此文件
 if(file.length()>1048576) //如果文件大於1M,重新創建一個文件
   continue;
   FileOutputStream foo=new FileOutputStream("yeeyoo.log"+i,true);//以append方式打開創建文件
   foo.write(logString.getBytes(),0,logString.length()); //寫入日誌字符串
   foo.close();
   break;//退出
}
   }catch(FileNotFoundException e){}
    catch(IOException e){}
}

}

登錄日誌的實現:

   下面再來看看我們的登錄Servlet中使用這個監聽器的部分源代碼:
   ……
   HttpSession session = req.getSession (true);
   ……
   ///////////////////////////////////////////////////////////////////////
   SessionListener sessionListener=new SessionListener(" IP:"+req.getRemoteAddr());  //對於每一個會話過程均啓動一個監聽器
       session.setAttribute("listener",sessionListener);  //將監聽器植入HttpSession,這將激發監聽器調用valueBound方法,從而記錄日誌文件。
  ///////////////////////////////////////////////////////////////////////
   當系統退出登錄時,只需簡單地調用session.removeAttribute(“listener”);即可自動調用監聽器的valueUnbound方法。或者,當Session Time Out的時候也會調用此方法。


登錄人數的統計:
ServletContext session1=getServletConfig().getServletContext();//取得ServletContext對象實例
      if((SessionListener)session1.getAttribute("listener1")==null)
      {
       SessionListener sessionListener1=new SessionListener("count");//只設置一次,不同於上面日誌文件的記錄每次會話均設置。即當第一個客戶連接到服務器時啓動一個全局變量,此後所有的客戶將使用相同的上下文。
       session1.setAttribute("listener1",sessionListener1);//將監聽器對象設置成ServletContext的屬性,具有全局範圍有效性,即所有的客戶均可以取得它的實例。
      }
      session.setAttribute("listener1",(SessionListener)session1.getAttribute("listener1"));//取出此全局對象,並且將此對象綁定到某個會話中,此舉將促使監聽器調用valueBound,計數器加一。
   在此後的程序中隨時可以用以下代碼取得當前的登錄人數:
   ((SessionListener)session.getAttribute("listener1")).getCount()
   getCount()是監聽器的一個方法,即取得當前計數器的值也就是登錄人數了。

-------------------------------------------------------------------------------->>>>>>>>>>


另一個代碼:

你應該對user object 實現HttpSessionBindingListener的valueBound和valueUnbound方法
____________________________________________________________
import javax.servlet.*;
import javax.servlet.http.*;

public class UseridWrapper implements HttpSessionBindingListener
{
public String userid = "0";
public User(String id)
{
this.userid = id;
}
public void valueBound(HttpSessionBindingEvent e)
{
   System.out.println("the user with id: "+this.userid+" logon!");
//here can use one Singleton object to manage the user list,
  //ex: UserManager.add(this);

}
public void valueUnbound(HttpSessionBindingEvent e)
{
  System.out.println("the user with id"+this.userid+"  exit!");
  //here can use one Singleton object to manage the user list,
  //ex: UserManager.remover(this);
}
}
//______________________________________________________________
使用:
User user=new User("1");
session.setAttribute("Login",);//觸發valueBound事件
使用:
session.invalidate() or session is timeout 觸發valueUnbound()
>>>>>>
//______________________________________________________________
使用:
UseridWrapper user=new UseridWrapper ("1");
session.setAttribute("Login",user);//觸發valueBound事件
使用:
session.invalidate() or session is timeout 觸發valueUnbound()

   以上代碼基本可實現在線統計功能,加以修改就可以了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章