监听器监听在线人数

思想: 

如何记录在线人数量:

       只要有一个session创建,则数量+1.

第一步:创建监听器

package czb.listener;

import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

 

public class SessionListenerDemo implements HttpSessionListener {

    // 当容器创建一个session时,由容器调用这个方法

    public void sessionCreated(HttpSessionEvent se) {

        // 统计在线人数

        ServletContext context = se.getSession().getServletContext();

        AtomicInteger count = (AtomicInteger) context.getAttribute("count");

        if (count == null) {

            count= newAtomicInteger(1);

        }else{

            count.addAndGet(1);

        }

        context.setAttribute("count",count);

    }

    // session过期,或执行了sessioninvalide(注销)方法时由容器来调用这个方法

    public void sessionDestroyed(HttpSessionEvent se) {

        HttpSession s = se.getSession();

        // 统计在线人数

        ServletContext context = se.getSession().getServletContext();

        AtomicInteger count = (AtomicInteger) context.getAttribute("count");

        count.addAndGet(-1);

        context.setAttribute("count",count);

    }

}

第二步:配置web.xml

<listener>

   <listener-class>czb.listener.SessionListenerDemo</listener-class>

  </listener>

第三步:显示页面

<body>

  在线人数:${count.get()}

</body>

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 Java Web 应用程序,用于连接 MySQL 数据库并监听在线人数: 1. 在 pom.xml 文件中添加 MySQL Connector/J 依赖: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> ``` 2. 在 web.xml 文件中添加 MySQL 数据库连接池: ```xml <resource-ref> <res-ref-name>jdbc/mysql</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> <resource-env-ref> <resource-env-ref-name>jdbc/mysql</resource-env-ref-name> <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type> </resource-env-ref> ``` 3. 在 context.xml 文件中配置 MySQL 数据库连接池: ```xml <Context> <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource" maxTotal="100" maxIdle="30" maxWaitMillis="10000" driverClassName="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/yourdatabase?useSSL=false&serverTimezone=UTC" username="yourusername" password="yourpassword"/> </Context> ``` 4. 编写 Java 代码,用于查询当前在线用户数量: ```java package com.example; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.sql.DataSource; @WebListener public class OnlineUserListener implements ServletContextListener { private DataSource dataSource; private Connection connection; public void contextInitialized(ServletContextEvent event) { try { Context context = new InitialContext(); dataSource = (DataSource) context.lookup("java:comp/env/jdbc/mysql"); connection = dataSource.getConnection(); } catch (NamingException | SQLException e) { e.printStackTrace(); } // 每隔 10 秒钟查询一次在线用户数量 Thread thread = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } int count = getOnlineUserCount(); event.getServletContext().setAttribute("onlineUserCount", count); } } }); thread.start(); } public void contextDestroyed(ServletContextEvent event) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } private int getOnlineUserCount() { int count = 0; try (PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM online_users"); ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { count = resultSet.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return count; } } ``` 这个监听器在应用程序启动时会创建一个 MySQL 数据库连接,并启动一个线程,每隔 10 秒钟查询一次在线用户数量,并将结果保存到 ServletContext 中。你可以在 JSP 或 Servlet 中使用以下代码来获取在线用户数量: ```java int count = (int) getServletContext().getAttribute("onlineUserCount"); ``` 这样,你就可以在 Java Web 应用程序中连接 MySQL 数据库并监听在线人数了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值