---
title: "HttpSessionListener统计在线人数"
author: "fanjava"
date: "2004-08-31T22:01:00Z"
tags: []
slug: "httpsessionlistener"
draft: false
lastmod: "2004-08-31T22:01:00Z"
id: 601906
url: "https://fanjava.iteye.com/blog/601906"
---

/\**  
\* 编写以下SessionCounter.java  
\* 并编译为SessiionCounter.class  
\* 然后放到你的网站的classpath的  
\* SessionCount(自己建立此目录)下面  
\*/

package SessionCount;  
import javax.servlet.\*;  
import javax.servlet.http.\*;

public class SessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {  
activeSessions++;  
}

public void sessionDestroyed(HttpSessionEvent se) {  
if(activeSessions &gt; 0)  
activeSessions--;  
}

public static int getActiveSessions() {  
return activeSessions;  
}  
}

接着建立online.jsp文件用于显示在线人数  
&lt;%@ page import="SessionCount.SessionCounter" %&gt;  
在线：&lt;%= SessionCounter.getActiveSessions() %&gt;

然后需要在你的网站的WEB-INF中建立web.xml  
文件内容如下：  
&lt;!-- Web.xml --&gt;  
&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;

&lt;!DOCTYPE web-app  
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
"http://java.sun.com/j2ee/dtds/web-app\_2.3.dtd"&gt;

&lt;web-app&gt;

&lt;!-- Listeners --&gt;  
&lt;listener&gt;  
&lt;listener-class&gt;  
SessionCount.SessionCounter  
&lt;/listener-class&gt;  
&lt;/listener&gt;

&lt;/web-app&gt;

然后重新启动你的应用服务器，访问online.jsp检查是否显示正确。