public class MySessionListener implementsHttpSessionListener {/*** 创建session*/@SuppressWarnings({"rawtypes", "unchecked"})public voidsessionCreated(HttpSessionEvent event) {
HttpSession session=event.getSession();
ServletContext application=session.getServletContext();//在application范围由一个HashSet集保存所有的session
HashSet sessions = (HashSet) application.getAttribute("sessions");if (sessions == null) {
sessions= newHashSet();
application.setAttribute("sessions", sessions);
}//新创建的session均添加到HashSet集中
sessions.add(session);//可以在别处从application范围中取出sessions集合//然后使用sessions.size()获取当前活动的session数,即为“在线人数”
}/*** 销毁session*/@SuppressWarnings("rawtypes")public voidsessionDestroyed(HttpSessionEvent event) {
HttpSession session=event.getSession();
ServletContext application=session.getServletContext();
HashSet sessions= (HashSet) application.getAttribute("sessions");//销毁的session均从HashSet集中移除
sessions.remove(session);
}/*** 获取系统在线用户数及登录用户数
*@paramrequest 当前请求对象
*@paramflag=1当前在线用户数 flag=2当前登录用户数
*@return
*/@SuppressWarnings("rawtypes")public static int getMaxUser(HttpServletRequest request,intflag){
HttpSession session=request.getSession();
ServletContext application=session.getServletContext();
HashSet sessions=(HashSet)application.getAttribute("sessions");int countUser =sessions.size();//System.out.println("###################当前在线人数:"+sessions.size());//String onlineuser = "";
int countOnlineUser = 0;for(Iterator it =(Iterator) sessions.iterator(); it.hasNext();){
HttpSession se=(HttpSession) it.next();if(se!=null){
UserInfo ui= (UserInfo) se.getAttribute("USER_INFO");if(ui!=null){//onlineuser += "___"+ui.getName();
countOnlineUser++;
}
}
}//System.out.println("###################当前登录用户:"+onlineuser);
return flag==1?countUser:countOnlineUser;
}