import javax.servlet.ServletContext;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;
public class WebSessionListener implements HttpSessionListener {
private static final String ONLINE_USERS_COUNT = "ONLINE_USERS_COUNT";
public void sessionCreated(HttpSessionEvent arg0) { // ServletContext servletContext = arg0.getSession().getServletContext(); int count; if (servletContext.getAttribute(ONLINE_USERS_COUNT)!=null) { count = ((Integer) servletContext.getAttribute(ONLINE_USERS_COUNT)).intValue() + 1; } else { count = 1; } System.out.println("-------------session created online users count= " + count); servletContext.setAttribute(ONLINE_USERS_COUNT, new Integer(count)); }
public void sessionDestroyed(HttpSessionEvent arg0) { // ServletContext servletContext = arg0.getSession().getServletContext(); int count; Integer countInteger = (Integer) servletContext.getAttribute(ONLINE_USERS_COUNT); if (countInteger!=null && (countInteger).intValue()>0) { count = (countInteger).intValue() - 1; } else { count = 0; } System.out.println("-------------session Destroyed online users count= " + count); servletContext.setAttribute(ONLINE_USERS_COUNT, new Integer(count)); }
}web.xml <!-- HttpSession listener 统计当前在线用户数 --> <listener> <listener-class>web.listener.WebSessionListener</listener-class> </listener>就这么简单!