javaweb统计在线人数,代码如下,不知道哪里出了问题,有时候显示在线人数为-1
/* Session创建事件 */
public void sessionCreated(HttpSessionEvent event) {
// TODO Auto-generated method stub
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);
}
/* Session失效事件 */
public void sessionDestroyed(HttpSessionEvent event) {
// TODO Auto-generated method stub
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);
}
jsp页面:
当前在线人数有<%=application.getAttribute("numSessions") %> 人
求指教,谢谢!