實作類別:OnLineUser .java
package com.alpha.onLineUser;</p><p>/*<br /> * Info:統計當前線上人數<br /> * Date:2010-4-5 17:45:55<br /> * Auth:JavaAlpha<br /> */</p><p>import javax.servlet.ServletContext;<br />import javax.servlet.http.HttpSession;<br />import javax.servlet.http.HttpSessionEvent;<br />import javax.servlet.http.HttpSessionListener;</p><p>public class OnLineUser implements HttpSessionListener<br />{<br />public void sessionCreated(HttpSessionEvent event)<br />{<br />ServletContext sct = event.getSession().getServletContext();</p><p>Integer onLineUser = (Integer) sct.getAttribute("onLineUser");<br />if (null == onLineUser) {<br />onLineUser = new Integer(1);<br />}else {<br />int count = onLineUser.intValue();<br />onLineUser = new Integer(count+1);<br />}<br />sct.setAttribute("onLineUser", onLineUser);<br />}</p><p>public void sessionDestroyed(HttpSessionEvent event)<br />{<br />ServletContext sct = event.getSession().getServletContext();<br />Integer onLineUser = (Integer) sct.getAttribute("onLineUser");<br />if (null == onLineUser) {<br />onLineUser = new Integer(0);<br />}else {<br />int count = onLineUser.intValue();<br />onLineUser = new Integer(count-1);<br />}<br />sct.setAttribute("onLineUser", onLineUser);</p><p>//銷毀session<br />// HttpSession session = event.getSession();<br />// session.invalidate();<br />}<br />}
JSP頁面:test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><br /><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><br /><html><br /> <body><br /> 當前線上人數:<%=application.getAttribute("onLineUser") %><br /> </body><br /></html><br />
web.xml 監聽器配置:
<!-- 統計當前線上人數 --><br /><listener><br /><listener-class>com.webapp.onLineUser.OnLineUser</listener-class><br /></listener>