[javaweb]监听器统计网页在线人数

监听器

1.配置监听器

package com.javaweb.controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.io.PushbackInputStream;

/**
 * @author panglili
 * @create 2022-07-20-21:03
 */
public class Listener implements HttpSessionListener {
    //session创建
    public void sessionCreated(HttpSessionEvent hE) {
        ServletContext context = hE.getSession().getServletContext();
        Integer o = (Integer)context.getAttribute("onlinecount");
            if(o==null){
                o=new Integer(1);
            }else{
                int count=o.intValue();
                o=new Integer(count+1);
            }
            context.setAttribute("o",o);
    }

    public void sessionDestroyed(HttpSessionEvent hE) {
        ServletContext context = hE.getSession().getServletContext();
        Integer o = (Integer)context.getAttribute("onlinecount");
        if(o==null){
            o=new Integer(1);
        }else{
            int count=o.intValue();
            o=new Integer(count+1);
        }
        context.setAttribute("o",o);
    }
    }

2.前台实现人数统计

<%--
  Created by IntelliJ IDEA.
  User: 塔塔
  Date: 2022/7/20
  Time: 21:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>people count:<%= getServletConfig().getServletContext().getAttribute("o")%>...</h1>
</body>
</html>

3.配置web

<listener>
    <listener-class>com.javaweb.controller.Listener</listener-class>
</listener>

posted @ 2022-07-23 18:30  路漫漫qixiuyuanxi  阅读(172)  评论(0编辑  收藏  举报