javaee HttpSessionListener监听器统计在线人数

news2024/9/22 15:41:21

在这里插入图片描述

先创建ServletContextListener

在全局对象application中设置count属性

package com.yyy.listener;

import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Application Lifecycle Listener implementation class TestServletContextListener
 *
 */
@WebListener
public class TestServletContextListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public TestServletContextListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("服务器关闭了");
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	// TODO Auto-generated method stub
    			//初始化数据 变量  数据库连接信息  连接池的信息
    			ServletContext application=  arg0.getServletContext();
    			
    			application.setAttribute("count", 0);
    			
    			
    			System.out.println("服务器启动了");
    }
	
}

创建SessionListener修改count的值

所有的session共用一个application对象

package com.yyy.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;

/**
 * Application Lifecycle Listener implementation class HttpSessionListener
 *
 */
@WebListener
public class HttpSessionListener implements javax.servlet.http.HttpSessionListener {

    /**
     * Default constructor. 
     */
    public HttpSessionListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent arg0)  { 
         // TODO Auto-generated method stub
    	ServletContext application=  arg0.getSession().getServletContext();
		
		int count=(int)application.getAttribute("count");
		
		count++;
		
		application.setAttribute("count", count);
		
		System.out.println("新用户上线,当前总人数为:"+count);
    }

	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
         // TODO Auto-generated method stub
    	 ServletContext application=  arg0.getSession().getServletContext();
 		
 		int count=(int)application.getAttribute("count");
 		
 		count--;
 		
 		application.setAttribute("count", count);
 		
 		System.out.println("用户下线,当前总人数为:"+count);
    }
	
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>web5</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <listener>
    <listener-class>com.yyy.listener.TestServletContextListener</listener-class>
  </listener>
  <session-config>
    <session-timeout>1</session-timeout>
  </session-config>
</web-app>

创建servlet运行测试

package com.yyy.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=request.getSession();
		System.out.println(session.getId()+":上线了");
		
//		ServletContext application=  session.getServletContext();
//		
//		int count=(int)application.getAttribute("count");
//		
//		System.out.println("在线人数为:"+count);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/697567.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

易基因|表观遗传学与脑卒中:DNA甲基化的作用及衰老对血脑屏障修复的影响

大家好&#xff0c;这里是专注表观组学十余年&#xff0c;领跑多组学科研服务的易基因。 脑卒中&#xff08;俗称中风&#xff09;是导致死亡和长期残疾的主要原因&#xff0c;尤其是对于老龄人来说。脑卒中的平均生存时间为6-7年&#xff0c;许多患者存在身体残疾和晚期认知功…

技术岗/算法岗面试如何准备?5000字长文、6个角度以2023秋招经历分享面试经验

技术岗/算法岗面试流程是什么样的&#xff1f;技术面都干什么&#xff1f;Coding 机试如何准备&#xff1f;技术面考察哪些知识&#xff0c;如何准备&#xff1f;项目八股如何准备&#xff1f;简历要注意什么&#xff1f;怎么做&#xff1f; 大家好&#xff0c;我是卷了又没卷…

uniapp 适配全面屏

1、manifest.json 文件修改 app-plus 下 添加 "safearea": {"background": "#00000000","bottom": {"offset": "auto"}},2、部分页面设置全屏&#xff08;登录页面&#xff09; methods: {//设置页面全屏onShow(…

SpringBoot(二)starter介绍

做Java后端的同学可能都知道&#xff0c;在SpringBoot诞生之前&#xff0c;还有传统的Spring。这种Spring项目想要运行&#xff0c;需要导入各种依赖&#xff0c;而且还要在 XML 配置文件中一顿配置&#xff0c;非常痛苦。但通过上篇博客我们可以看到&#xff0c;SpringBoot项目…

事务与隔离级别

事务四要素 原子性&#xff08;Atomicity&#xff09;&#xff1a;要么全部完成&#xff0c;要么全部不完成&#xff1b;一致性&#xff08;Consistency&#xff09;&#xff1a;一个事务单元需要提交之后才会被其他事务可见&#xff1b;隔离性&#xff08;Isolation&#xff…

azure databricks因为notebook 日志打多或者打印图片太多,往下拉卡死怎么处理

1、同事碰到个问题&#xff0c;databricks 页面卡死不动了 2、我。。。。。。。。测试了下搞不定&#xff0c;找azure的工程师&#xff0c;特此笔记如下图 !](https://img-blog.csdnimg.cn/5db9756d0e224d15a9a607561b47591f.png)

怎样自定义starter模块和使用

一、 自定义Starter模块 在实际开发中&#xff0c;经常会定义一些公共组件&#xff0c;提供给各个项目团队使用。而在SpringBoot的项目中&#xff0c;一般会将这些公共组件封装为SpringBoot的starter(起步依赖)。 1.1实例–阿里云OSS的配置 前言&#xff1a;我们在使用阿里云…

windows下MySQL 5.7.31的安装

文章目录 安装步骤检查是否安装成功配置环境变量 安装步骤 双击安装包mysql-installer-community-5.7.31.0.msi选择自定义安装“custom”&#xff0c;点击next “Developer Default”是开发者默认“Server only”仅作为服务器安装“Clientonly”仅作为客户端安装“Full”是完…

华为OD机试真题 Python 实现【红黑图】【2023Q1 200分】,附详细解题思路

一、题目描述 众所周知红黑树是一种平衡树&#xff0c;它最突出的特性就是不能有两个相邻的红色节点。 那我们定义一个红黑图&#xff0c;也就是一张无向图中&#xff0c;每个节点可能有红黑两种颜色&#xff0c;但我们必须保证没有两个相邻的红色节点。 现在给出一张未染色的…

晶振的作用,高速晶振优缺点

前言 &#xff08;1&#xff09;我们都知道晶振是一款MCU的心脏&#xff0c;因为长期用这种抽象的概念进行解释&#xff0c;导致很多人不知道这个心脏的实际作用。因此&#xff0c;我在这里详细的介绍一下晶振对于MCU的实际作用。 &#xff08;2&#xff09;接下来我将会在MCU处…

一零六一、Jupyter notebook文件默认路径修改方法

1 .打开 Anaconda Prompt&#xff0c;输入命令 jupyter notebook --generate-config 根据上面运行处的路径打开 C:\Users\WW.jupyter\jupyter_notebook_config.py文件&#xff0c;可以使用记事本打开。 2 .直接CtrlF 搜索 &#xff0c;找到 #c.NotebookApp.notebook_dir ‘’…

Spring 2023面试题(2)--Spring mvc 运行流程

1. Spring MVC的运行流程主要包括以下步骤&#xff1a; 用户发送请求到前端控制器&#xff08;DispatcherServlet&#xff09;。前端控制器接收到请求后&#xff0c;初始化处理器映射器&#xff08;HandlerMapping&#xff09;和处理器适配器&#xff08;HandlerAdapter&#…

Crypto(小学期培训)

你被骗了 url编码直接解 进入网站、找到时间 flag{2020-01-01 07:43:23} 梅开二度 凯撒密码 y和h相差17 三羊开泰 词频分析 这是&#xff1f;&#xff1f;&#xff1f; 010编辑器打开 上面是密文 下面是密码表64个&#xff0c;想到base64 找到原来的数值 与之对应&a…

JVM GC ROOT分析与垃圾收集器原理分析(三)

目录 一、GC ROOT 1、虚拟机栈中的本地变量 2、static 成员 3、常量引用 4、本地方法栈中的变量 5、类加载器 6、线程 二、回收算法 1、标记和清除 2、复制算法 3、标记整理 三、垃圾收集器 1、新生代-复制算法 2、老年代-标记清除/整理 3、垃圾收集器分类 1、…

Python如何向一个空列表中append列表

最近在做回溯组合问题时–力扣链接&#xff0c;遇到了向一个空列表中append多个列表。 于是&#xff0c;我原来的代码是&#xff1a; def main(n,k):result []temp []def backtrack(n,k,startIndex):if(len(temp)k):result.append(temp)returnfor i in range(startIndex,n1)…

group by rollup

group by rollup rollup与group by组合使用可对分组结果进行进一步的汇总(相当于对分组结果加一行小计)。 mysql : SELECT CASE WHEN GROUPING(姓名)1 THEN 总计 ELSE 姓名 END AS 姓名, SUM(数值1) 统计数值1, SUM(数值2) 统计数值2 FROM 表名 GROUP BY 姓名 WITH ROLLUPora…

SpringCloud微服务项目实战(一)---搭建SpringBoot项目

目录 SpringBoot与SpringCloud的关系环境配置开始搭建SpringBoot项目问题总结 SpringBoot与SpringCloud的关系 Spring Boot主内&#xff0c;能够快速搭建&#xff0c;快速开发单个微服务&#xff0c;搞定了数据层访问、RESTful 接口、日志组件、内置容器等等基础功能Spring Cl…

shardingsphere-proxy 实现mysql单库分表

1、docker安装mysql5.7版本 拉取mysql的镜像 docker pull mysql:5.7创建mysql的配置目录&#xff0c;日志目录&#xff0c;数据存储的目录 mkdir -p /home/sunyuhua/docker/mysql/conf mkdir -p /home/sunyuhua/docker/mysql/logs mkdir -p /home/sunyuhua/docker/mysql/dat…

微信小游戏:超大数值计算

测试代码&#xff1a; import {large_number} from "./large_number";const {ccclass, property} cc._decorator;ccclass export default class NewClass extends cc.Component {property(cc.Label)label: cc.Label null;propertytext: string hello;// LIFE-CYCL…

操作符重载的概念

下面的复数解决方案是否可行&#xff1f; Add 函数可以解决 Complex 对象相加的问题&#xff0c;但是 Complex 是现实世界中确实存在的复数&#xff0c;并且复数在数学中的地位和普通的实数相同 为什么不能让 操作符也支持复数相加呢&#xff1f; 操作符重载 C 中的重载能够…