通过web.xml配置session的监听,每当监听到一个新的session,则计数加1。
反之当程序失去一个session则计数减1.
OnlineCounter类,这个类需要实现HttpSessionListener, HttpSessionAttributeListener, HttpSessionBindingListener三个接口:
/**
* OnlineCounter.java
*
* Copyright 2008. All Rights Reserved.
*/
package com.cosmow.online;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* TODO OnlineCounter 记录在线人数
*
* Revision History
*
* 2008-8-11,Cosmo,created it
*/
public class OnlineCounter extends HttpServlet implements HttpSessionListener,
HttpSessionAttributeListener, HttpSessionBindingListener {
private static final long serialVersionUID = 1L;
private static int sessionCounter = 0;
private static int attributeCounter = 0;
public void sessionCreated(HttpSessionEvent event) {
sessionCounter++;
System.out.println("session created");
}
public void sessionDestroyed(HttpSessionEvent event) {
sessionCounter--;
System.out.println("session destroied");
}
public void attributeAdded(HttpSessionBindingEvent event) {
attributeCounter++;
System.out.println("attribute added");
}
public void attributeRemoved(HttpSessionBindingEvent event) {
attributeCounter--;
System.out.println("attribute removed");
}
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println(event.getName() + " replaced");
}
public void valueBound(HttpSessionBindingEvent event) {
System.out.println(event.getName() + " bound " + event.getValue());
}
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println(event.getName() + " unbound " + event.getValue());
}
// 获取当前在线人数
public static int getOnlineSession() {
return sessionCounter;
}
public static int getOnlineAttribute() {
return attributeCounter;
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>com.cosmow.online.OnlineCounter</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>