Session代表客戶的會話過程,客戶登錄時,往Session中傳入一個對象,即可跟蹤客戶的會話。在Servlet中,傳入Session的對象假如是一個實現(xiàn)HttpSessionBindingListener接口的對象(方便起見,此對象稱為監(jiān)聽器),則在傳入的時候(即調(diào)用HttpSession對象的setAttribute方法的時候)和移去的時候(即調(diào)用HttpSession對象的removeAttribute方法的時候或Session Time out的時候)Session對象會自動調(diào)用監(jiān)聽器的valueBound和valueUnbound方法(這是HttpSessionBindingListener接口中的方法)。
由此可知,登錄日志也就不難實現(xiàn)了。
另外一個問題是,如何統(tǒng)計在線人數(shù),這個問題跟實現(xiàn)登錄日志稍微有點不同,統(tǒng)計在線人數(shù)(及其信息),就是統(tǒng)計現(xiàn)在有多少個Session實例存在,我們可以增加一個計數(shù)器(假如想存儲更多的信息,可以用一個對象來做計數(shù)器,隨后給出的實例中,簡單起見,用一個整數(shù)變量作為計數(shù)器),通過在valueBound方法中給計數(shù)器加1,valueUnbound方法中計數(shù)器減1,即可實現(xiàn)在線人數(shù)的統(tǒng)計。當然,這里面要利用到ServletContext的全局特性。(有關ServletContext的敘述請參考Servlet規(guī)范),新建一個監(jiān)聽器,并將其實例存入ServletContext的屬性中,以保證此監(jiān)聽器實例的唯一性,當客戶登錄時,先判定ServletContext的這個屬性是否為空,假如不為空,證實已經(jīng)創(chuàng)建,直接將此屬性取出放入Session中,計數(shù)器加1;假如為空則創(chuàng)建一個新的監(jiān)聽器,并存入ServletContext的屬性中。
舉例說明:
實現(xiàn)一個監(jiān)聽器:
// SessionListener.java
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
//監(jiān)聽登錄的整個過程
public class SessionListener implements HttpSessionBindingListener
{
public String private String logString=""; //日志記錄字符串
private int count=0; //登錄人數(shù)計數(shù)器
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(); //假如文件不存在,創(chuàng)建此文件
if(file.length()>1048576) //假如文件大于1M,重新創(chuàng)建一個文件
continue;
FileOutputStream foo=new FileOutputStream("yeeyoo.log"+i,true);//以append方式打開創(chuàng)建文件
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(); //假如文件不存在,創(chuàng)建此文件
if(file.length()>1048576) //假如文件大于1M,重新創(chuàng)建一個文件
continue;
FileOutputStream foo=new FileOutputStream("yeeyoo.log"+i,true);//以append方式打開創(chuàng)建文件
foo.write(logString.getBytes(),0,logString.length()); //寫入日志字符串
foo.close();
break;//退出
}
}catch(FileNotFoundException e){}
catch(IOException e){}
}
新聞熱點
疑難解答