冰浪

          哥已不再年輕 - 堅定夢想,畢生追求!
          posts - 85, comments - 90, trackbacks - 0, articles - 3
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          用HttpSessionAttributeListener接口實現在線統計

          Posted on 2007-07-11 20:33 冰浪 閱讀(3326) 評論(0)  編輯  收藏 所屬分類: WEB開發

          以下是一些不詳細的代碼,主要是說明原理:
          捕獲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()

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

          主站蜘蛛池模板: 石棉县| 锡林郭勒盟| 辽中县| 无极县| 藁城市| 鞍山市| 安西县| 博客| 瑞丽市| 荃湾区| 石柱| 洛浦县| 星座| 渭源县| 竹溪县| 竹山县| 罗甸县| 兴文县| 辉县市| 阜南县| 武冈市| 四会市| 涿州市| 武隆县| 顺义区| 平远县| 平定县| 米脂县| 乌拉特后旗| 安西县| 永吉县| 商丘市| 息烽县| 泾阳县| 交城县| 慈溪市| 鄢陵县| 峡江县| 海林市| 桓台县| 海宁市|