1、创建监听器,重写里面的方法
package com.xiaocong.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计在线人数:统计session
public class OnlineCountListener implements HttpSessionListener {
//创建Session监听
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext sc = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) sc.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount=new Integer(1);
}else{
int count=onlineCount.intValue();
onlineCount=new Integer(count+1);
}
sc.setAttribute("OnlineCount",onlineCount);
}
//销毁Session监听
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext sc = httpSessionEvent.getSession().getServletContext();
System.out.println(httpSessionEvent.getSession().getId());
Integer onlineCount = (Integer) sc.getAttribute("OnlineCount");
httpSessionEvent.getSession().invalidate();
if(onlineCount==null){
onlineCount=new Integer(0);
}else{
int count=onlineCount.intValue();
onlineCount=new Integer(count-1);
}
sc.setAttribute("OnlineCount",onlineCount);
}
}
2、在web.xml中注册
com.xiaocong.listener.OnlineCountListener
60
3、在网页上显示出来
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$
当前有<%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%>人在线



