实现类:OnLineUser .java
package com.alpha.onLineUser; /* * Info:统计当前在线人数 * Date:2010-4-5 17:45:55 * Auth:JavaAlpha */ import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class OnLineUser implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { ServletContext sct = event.getSession().getServletContext(); Integer onLineUser = (Integer) sct.getAttribute("onLineUser"); if (null == onLineUser) { onLineUser = new Integer(1); }else { int count = onLineUser.intValue(); onLineUser = new Integer(count+1); } sct.setAttribute("onLineUser", onLineUser); } public void sessionDestroyed(HttpSessionEvent event) { ServletContext sct = event.getSession().getServletContext(); Integer onLineUser = (Integer) sct.getAttribute("onLineUser"); if (null == onLineUser) { onLineUser = new Integer(0); }else { int count = onLineUser.intValue(); onLineUser = new Integer(count-1); } sct.setAttribute("onLineUser", onLineUser); //销毁session // HttpSession session = event.getSession(); // session.invalidate(); } }
JSP页面:test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> 当前在线人数:<%=application.getAttribute("onLineUser") %> </body> </html>
web.xml 监听器配置:
<!-- 统计当前在线人数 --> <listener> <listener-class>com.webapp.onLineUser.OnLineUser</listener-class> </listener>