zoukankan      html  css  js  c++  java
  • 使用ServletContextListener和HttpSessionListener两种监听器实现记录当前网站在线人数

    web.xml中配置:

     <listener>
       <listener-class>com.mcm.listener.ServletContextListenerImpl</listener-class>
      </listener>
      <listener>
       <listener-class>com.mcm.listener.HttpSessionListenerImpl</listener-class>
      </listener>

    ServletContextListenerImpl类:

    package com.mcm.listener;

    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;

    public class ServletContextListenerImpl implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent event) {
      ServletContext application = event.getServletContext();
      application.removeAttribute("onLineNum");
    }

    public void contextInitialized(ServletContextEvent event) {
      int num = 0;
      ServletContext application = event.getServletContext();
      application.setAttribute("onLineNum", num);
    }

    }

    HttpSessionListenerImpl类:

    package com.mcm.listener;

    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;

    public class HttpSessionListenerImpl implements HttpSessionListener {

     public void sessionCreated(HttpSessionEvent event) {
      ServletContext application = event.getSession().getServletContext();
      Integer num = (Integer) application.getAttribute("onLineNum");
      if(num != null){
       int count = num;
       count = count + 1;
       application.setAttribute("onLineNum", count);
      }
     }

     public void sessionDestroyed(HttpSessionEvent event) {
      ServletContext application = event.getSession().getServletContext();
      Integer num = (Integer) application.getAttribute("onLineNum");
      int count = num;
      count = count - 1;
      application.setAttribute("onLineNum", count);
      
     }

    }

    index.jsp中:

    当前在线人数:${onLineNum }

    结果:

  • 相关阅读:
    C# Net Core 使用 ClientWebSocket 实现 WebSocket 客户端
    C# Net 使用 RSA 加密解密 OpenSSL 生成的密码
    VS 代码提示默认不选中 解决办法
    C# While 超时设置
    C# 比较日期格式中的年月大小
    C#实现QQ邮箱IMAP之邮件处理
    Windwos服务之定时发送邮件(一)
    js基于“合成大西瓜的”碰撞模型(一)
    Windows下,通过运行直接打开软件
    C#爬取国家统计局五级地址
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3201138.html
Copyright © 2011-2022 走看看