监听器(统计在线人数)

监听器(统计在线人数)

监听器是GUI中常用的功能,Javaweb中使用场景不是很多,可以使用监听器实现统计网站访问人数;

实现原理

服务器回味每个客户端创建一个session,通过监听服务器中session的创建和销毁便可以记录当前访问网站的人数;

实现步骤

  • 实现HttpSessionListener类

    package com.kangzhu.listener;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    public class OnlineCountListener implements HttpSessionListener {
    
        public void sessionCreated(HttpSessionEvent se) {
            ServletContext servletContext = se.getSession().getServletContext();
            Integer count = (Integer) servletContext.getAttribute("count");
            if (count == null) {
                count = 1;
            }else {
                count += 1;
            }
            servletContext.setAttribute("count", count);
        }
    
        public void sessionDestroyed(HttpSessionEvent se) {
            ServletContext servletContext = se.getSession().getServletContext();
            Integer count = (Integer) servletContext.getAttribute("count");
            if (count == null) {
                count = 0;
            }else {
                count -= 1;
            }
            servletContext.setAttribute("count", count);
        }
    }
    

    对Session的监听需要实现两个方法,Session的创建和销毁,需要注意的是需要将统计的在线人数存放在ServletContext对象中;

  • 在web.xml中进行注册

    <listener>
        <listener-class>com.kangzhu.listener.OnlineCountListener</listener-class>
    </listener>
    
  • 前端获取访问人数

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
      </head>
      <body>
      <h1>当前网站的有<%=request.getSession().getServletContext().getAttribute("count")%>人访问</h1>
      </body>
    </html>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值