Servlet的监听器实现在线人数统计

朱雀 2021-07-24 17:35 501阅读 0赞

目录

一 开发步骤

二 实战

三 测试


一 开发步骤

1 编写监听器

2 注册监听器

二 实战

1 监听器编写

  1. import javax.servlet.ServletContext;
  2. import javax.servlet.http.HttpSessionEvent;
  3. import javax.servlet.http.HttpSessionListener;
  4. /**
  5. * @ClassName: OnlineCount
  6. * @Description: 在线人数监听
  7. * @Date: 2020/6/15
  8. * @Author: cakin
  9. */
  10. public class OnlineCount implements HttpSessionListener {
  11. /**
  12. * 功能描述:会话创建时刻进行监听
  13. *
  14. * @param se 会话事件
  15. * @author cakin
  16. * @date 2020/6/15
  17. * @description: 创建一个会话时,在线人数加1
  18. */
  19. public void sessionCreated(HttpSessionEvent se) {
  20. ServletContext servletContext = se.getSession().getServletContext();
  21. Integer onlineCount = (Integer) servletContext.getAttribute("onlineCount");
  22. System.out.println("增加一个session");
  23. if (onlineCount == null) {
  24. onlineCount = 1;
  25. } else {
  26. int count = onlineCount.intValue();
  27. onlineCount = ++count;
  28. }
  29. servletContext.setAttribute("onlineCount", onlineCount);
  30. }
  31. /**
  32. * 功能描述:会话销毁时刻进行监听
  33. *
  34. * @param se 会话事件
  35. * @author cakin
  36. * @date 2020/6/15
  37. * @description: 销毁会话时,在线人数建1
  38. */
  39. public void sessionDestroyed(HttpSessionEvent se) {
  40. ServletContext servletContext = se.getSession().getServletContext();
  41. System.out.println("减少一个session");
  42. Integer onlineCount = (Integer) servletContext.getAttribute("onlineCount");
  43. if (onlineCount == null) {
  44. onlineCount = 0;
  45. } else {
  46. int count = onlineCount.intValue();
  47. onlineCount = --count;
  48. }
  49. servletContext.setAttribute("onlineCount", onlineCount);
  50. }
  51. }

2 注册监听器

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <!--监听器所在的类-->
  7. <listener>
  8. <listener-class>OnlineCount</listener-class>
  9. </listener>
  10. <!--超时时间为1分钟-->
  11. <session-config>
  12. <session-timeout>1</session-timeout>
  13. </session-config>
  14. </web-app>

3 JSP页面测试

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>$Title$</title>
  5. </head>
  6. <body>
  7. <h1>当前在线人数为<%=this.getServletConfig().getServletContext().getAttribute("onlineCount")%></h1>
  8. </body>
  9. </html>

三 测试

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5ncWl1bWluZw_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,501人围观)

还没有评论,来说两句吧...

相关阅读

    相关 监听器统计在线人数

            接着,我来写一个监听器的案例来巩固学习监听器的知识,便于日后的查阅和复习。大概分为以下几个步骤: 1.编写统计人数的Servlet,实现特定的监听器接口 2