Java之Listener
2024-10-21 19:50:00
Java之Listener
Listener监听器
监听器有很多种,大部分还是在GUI用的比较多,这里简单记录一点关于HttpSessionListener的
统计session count Listener。主要通过ServletContext上下文来存储session count,在listener中create和destroyed方法实现session count的逻辑,主要是将ServletContext作为第三方来进行session count值的存储与改动。通过jsp中application对象get上下文属性来获取count值实现实时显示session的数量。
public class OnlineCountListener implements HttpSessionListener {
//创建session监听
//一旦创建session就会触发该事件
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println(httpSessionEvent.getSession().getId());
//每次有session创建,代表用户数量+1
HttpSession session = httpSessionEvent.getSession();
//获取上下文,将人数OnlineCount存入上下文中方便读写
ServletContext sct = session.getServletContext();
Integer OnlineCount = (Integer) sct.getAttribute("OnlineCount");
if (OnlineCount==null){
OnlineCount = new Integer(1);
}else {
int count = OnlineCount.intValue();
OnlineCount = new Integer(count+1);
}
//数值通过属性存入上下文中
sct.setAttribute("OnlineCount", OnlineCount);
}
//销毁session监听
//一旦销毁session就会触发该事件
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
//每次有session创建,代表用户数量+1
HttpSession session = httpSessionEvent.getSession();
//获取上下文,将人数OnlineCount存入上下文中方便读写
ServletContext sct = session.getServletContext();
Integer OnlineCount = (Integer) sct.getAttribute("OnlineCount");
if (OnlineCount==null){
OnlineCount = new Integer(0);
}else {
int count = OnlineCount.intValue();
OnlineCount = new Integer(count-1);
}
//数值通过属性存入上下文中
sct.setAttribute("OnlineCount", OnlineCount);
}
}
web.xml配置Listener
<listener>
<listener-class>com.zh1z3ven.listener.OnlineCountListener</listener-class>
</listener>
Index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>OnlineCount</title>
</head>
<body>
<h2 align="center">当前在线人数为:<span><%= application.getAttribute("OnlineCount")%></span></h2>
</body>
</html>
最新文章
- sqlite锁的机制
- MySQL备份方式简介
- H5 多个视频 循环播放效果
- display: block; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 0px; -webkit-margin-end: 0px;
- Cocos2d-x分类
- Bitmap介绍
- Google Maps Android API v2 (4)- 地图类型
- HTML超连接的使用
- 准备冲锋 golang入坑系列
- Linux 一块网卡配置多个IP的方法
- mysql添加字段
- wifi探针的使用说明.
- OpenCV-Python入门教程2-打开摄像头
- ASP.NET中HttpApplication中ProcessRequest方法中运行的事件顺序;ASP.NET WebForm和MVC总体请求流程图
- 再谈 linux 的sed用法
- JEECG中t:dictSelect的extendJson用法
- LeetCode——Maximum Binary Tree
- [转]Pass a ViewBag instance to a HiddenFor field in Razor
- Java LinkedList 和 ArrayList
- bzoj5039:[Jsoi2014]序列维护