用HttpSessionListener 。
package demo.listener;
import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener;
public class SessionCounter implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { ServletContext ctx = event.getSession( ).getServletContext( ); Integer numSessions = (Integer) ctx.getAttribute("numSessions"); if (numSessions == null) { numSessions = new Integer(1); } else { int count = numSessions.intValue( ); numSessions = new Integer(count + 1); } ctx.setAttribute("numSessions", numSessions); } public void sessionDestroyed(HttpSessionEvent event) { ServletContext ctx = event.getSession( ).getServletContext( ); Integer numSessions = (Integer) ctx.getAttribute("numSessions"); if (numSessions == null) { numSessions = new Integer(0); } else { int count = numSessions.intValue( ); numSessions = new Integer(count - 1); } ctx.setAttribute("numSessions", numSessions); } }
在这个解决方案中,任何一个Session被创建或者销毁时,都会通知SessionCounter 这个类,当然通知的原因是必须在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/dtd/web-app_2_3.dtd"> <web-app> <display-name>Struts Examples</display-name> <listener> <listener-class>demo.listener.SessionCounter </listener-class> </listener>
|