您的位置:首页 > 其它

SessionListener,据说是可以用来统计系统的在线人数

2018-01-01 21:19 344 查看
1、在web.xml中增加监听器

<listener>
        <listener-class>com.suning.web.authority.SessionListener</listener-class>

    </listener>

2、

package com.suning.web.authority;

public class SessionListener implements HttpSessionListener {

 

       public void sessionCreated(HttpSessionEvent event) {

              HttpSession session = event.getSession();

              ServletContext application = session.getServletContext();

              

              // 在application范围由一个HashSet集保存所有的session
              HashSet sessions = (HashSet) application.getAttribute("sessions");

              if (sessions == null) {

                     sessions = new HashSet();

                     application.setAttribute("sessions", sessions);

              }

              

              // 新创建的session均添加到HashSet集中
              sessions.add(session);

              // 可以在别处从application范围中取出sessions集合

              // 然后使用sessions.size()获取当前活动的session数,即为“在线人数”
       }

 

       public void sessionDestroyed(HttpSessionEvent event) {

              HttpSession session = event.getSession();

              ServletContext application = session.getServletContext();

              HashSet sessions = (HashSet) application.getAttribute("sessions");

              

              // 销毁的session均从HashSet集中移除
              sessions.remove(session);

       }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: