【Listener监听器】统计当前页面在线人数

在线人数统计

涉及的技术知识点

监听器

监听器

  1. Listener用于监听JavaWeb程序中的事件。

  2. 例如:ServletContext、HttpSession、ServletRequest的创建、修改和删除。

  3. 监听器的类型分为

    1. 生命周期
    2. 数据绑定

创建listener

@WebListener()
public class LoginListener implements HttpSessionListener {
    
    

    // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    public void sessionCreated(HttpSessionEvent se) {
    
    
        /* Session is created. */
        //ServletContext :Servlet上下文对象.
        //  WEB应用服务器会为每个web应用创建唯一一个ServletContext对象.
        //  在整个web应用中作用域最大且是所有的用户可共享的.
        //  ServletContext在web引用服务器启动则被创建, 服务器销毁此对象才会被销毁.


        //获取到ServletContext
        ServletContext sc = se.getSession().getServletContext();

        //我们会在ServletContext中绑定一个在线人数, 通过  count 这个key
        //尝试从Servletcontext中获取 count
        Object count = sc.getAttribute("count");
        if(count == null){
    
    
            sc.setAttribute("count",1);
        }else {
    
    
            sc.setAttribute("count",(Integer)count + 1);
        }
    }

    public void sessionDestroyed(HttpSessionEvent se) {
    
    

    }

main.jsp代码:

<body>
    <h1 align="center">欢迎<font color="red">${sessionScope.loginUser.username}</font>登录</h1>
    <br>
    <h2 align="center">当前在线人数:<font color="red">${applicationScope.count}</font>
</body>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43215322/article/details/109455405