zoukankan      html  css  js  c++  java
  • JavaWeb学习记录(二十六)——在线人数统计HttpSessionListener监听实现

    一、session销毁控制层代码

    public class InvalidateSession extends HttpServlet {

        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.getSession().invalidate();//执行销毁session的操作
        }

        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            this.doGet(request, response);

        }

    }

    二、监听代码

    public class MyHttpSessionListener implements HttpSessionListener {

        @Override
        public void sessionCreated(HttpSessionEvent arg0) {
            // 当前人数加1

            // 看ServletContext域中是否已经存储了count 如果没有是第一个人访问 ,如果有就加1
            // 获取存储域对 全局
            ServletContext context = arg0.getSession().getServletContext();
            // 获取指定属性名称的参数值
            Object obj = context.getAttribute("count");
            System.out.println(obj);
            if (obj == null) {
                context.setAttribute("count", 1);
            } else {
                int count = (Integer) obj;
                count++;
                context.setAttribute("count", count);
            }
        }

        /**
         * 当浏览器关闭的时候,不会调用此方法
         * 1.当session失效    session默认有效时间 30分钟
         * 2.执行了session.invalidate();
         */
        @Override
        public void sessionDestroyed(HttpSessionEvent arg0) {
            System.out.println("--------sessionDestroyed------");
            // 获取存储域对 全局
            ServletContext context = arg0.getSession().getServletContext();
            // 获取指定属性名称的参数值
            Object obj = context.getAttribute("count");
            if (obj != null) {
                int count = (Integer) obj;
                count--;
                context.setAttribute("count", count);
            }

        }

    }
    三、显示层代码

    <script type="text/javascript">
            //当关闭窗体前
            window.onbeforeunload = function(){
               //调用这个请求  去销毁session 当前会话的session
               window.location.href="http://localhost:8080/count/destorysession.do";
            };
        </script>

     <body>
           <%--
             ServletContext  setAttribute("count",count);
            --%>
           <h1>当前在线的人数是:${count}</h1>
      </body>

    当一个会话关闭时,在线人数会相应减少。如果没有一中的session销毁控制层代码和三中的javascript代码,则会话增多时,显示在线人数会增加,但会话减少时,没有响应,

    这是因为浏览器关闭时不会调用sessionDestroyed方法。

  • 相关阅读:
    作业2
    实验12——指针的基础应用2
    实验11——指针的基础应用
    实验十——一维数组的定义及引用
    实验九——基本数据类型存储及应用总结
    实验八--函数定义及调用总结
    实验七——函数定义及调用总结
    实验六——循环结构程序练习总结
    实验五——循环结构学习总结
    实验三——for 语句及分支结构else-if
  • 原文地址:https://www.cnblogs.com/ly-radiata/p/4414396.html
Copyright © 2011-2022 走看看