/**
* 编写以下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 > 0)
activeSessions--;
}
public static int getActiveSessions() {
return activeSessions;
}
}
接着建立online.jsp文件用于显示在线人数
<%@ page import="SessionCount.SessionCounter" %>
在线:<%= SessionCounter.getActiveSessions() %>
然后需要在你的网站的WEB-INF中建立web.xml
文件内容如下:
<!-- Web.xml -->
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.3.dtd">
<web-app>
<!-- Listeners -->
<listener>
<listener-class>
SessionCount.SessionCounter
</listener-class>
</listener>
</web-app>
<!--ShowApplication.jsp-->
<%@page import="java.util.*"%>
<html>
<head><title>Application Object Example</title></head>
<body bgcolor="white">
<%
Integer accessCount=(Integer)session.getAttribute("accessCount");
String heading=null;
if (accessCount==null){
accessCount=new Integer(1);
heading="Welcome,this is your First Visit";
}else{
accessCount=new Integer(accessCount.intValue()+1);
heading="Welcome,this is your Visit #"+accessCount;
}
session.setAttribute("accessCount",accessCount);
Integer totalAccessCount=(Integer)application.getAttribute("totalAccessCount");
if(totalAccessCount==null){
totalAccessCount=new Integer(1);
}else{
totalAccessCount=new Integer(totalAccessCount.intValue()+1);
}
application.setAttribute("totalAccessCount",totalAccessCount);
%>
<h1 align=center><%=heading%></h1>
<h2 align=center>Access Counts</h2>
<table border=1 align="center">
<tr bgcolor="#F9AD00">
<th>Info Type</th><th>Value</th>
</tr>
<tr>
<td>Your Accesses</td>
<td><%=accessCount%></td>
</tr>
<tr>
<td>Total Accesses</td>
<td><%=totalAccessCount%></td>
</tr>
</table>
</body>
</html>
这个是Application的应用,显示结果为:
Welcome,this is your First Visit
Access Counts
Info Type Value
Your Accesses 1
Total Accesses 1
还有在线人数直接取SessionID的数目就行了