---
title: "监听器实现网站流量统计"
author: "jackson_jar"
date: "2008-09-23T10:49:30Z"
tags: ["Web", "XML"]
slug: "untitled"
draft: false
lastmod: "2008-09-23T10:49:30Z"
id: 245766
url: "https://jackson-jar.iteye.com/blog/245766"
---

//test.Online  
public class Online implements HttpSessionListener{

public void sessionCreated(HttpSessionEvent arg0) {  
OnLineCount.raise();  
}

public void sessionDestroyed(HttpSessionEvent arg0) {  
OnLineCount.reduce();  
}

}

public class OnLineCount {

public static long onLineCount = 0;  
public static long currentOnLineCount = 0;  
public static OnLineCount oc =null;

public synchronized static void raise(){  
onLineCount++;  
currentOnLineCount++;  
}  
public synchronized static void reduce(){  
currentOnLineCount--;  
}

public synchronized long getCurrentOnLineCount(){  
return currentOnLineCount;  
}

public static synchronized OnLineCount getInstance(){  
if(oc == null)  
oc = new OnLineCount();  
return oc;  
}

}

//web.xml中加入监听  
&lt;listener&gt;  
  &lt;description&gt;HttpSessionListener&lt;/description&gt;  
  &lt;listener-class&gt;test.Online&lt;/listener-class&gt;  
&lt;/listener&gt;  
//web.xml中设置session过期时间 单位为 分钟  
  &lt;session-config&gt;  
        &lt;session-timeout&gt;3&lt;/session-timeout&gt;  
&lt;/session-config&gt;

test.java  
public class Test{  
public static void mian(String args\[]){  
  System.out.println("历史总访问人数:"+OnLineCount.onLineCount);  
   System.out.println("当前在线人数:"+OnLineCount.currentOnLineCount);  
}  
}