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>

最新文章

  1. sqlite锁的机制
  2. MySQL备份方式简介
  3. H5 多个视频 循环播放效果
  4. display: block; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 0px; -webkit-margin-end: 0px;
  5. Cocos2d-x分类
  6. Bitmap介绍
  7. Google Maps Android API v2 (4)- 地图类型
  8. HTML超连接的使用
  9. 准备冲锋 golang入坑系列
  10. Linux 一块网卡配置多个IP的方法
  11. mysql添加字段
  12. wifi探针的使用说明.
  13. OpenCV-Python入门教程2-打开摄像头
  14. ASP.NET中HttpApplication中ProcessRequest方法中运行的事件顺序;ASP.NET WebForm和MVC总体请求流程图
  15. 再谈 linux 的sed用法
  16. JEECG中t:dictSelect的extendJson用法
  17. LeetCode——Maximum Binary Tree
  18. [转]Pass a ViewBag instance to a HiddenFor field in Razor
  19. Java LinkedList 和 ArrayList
  20. bzoj5039:[Jsoi2014]序列维护

热门文章

  1. [心得体会]jvm
  2. [转载]API网关
  3. python pycharm 正则表达式批量替换
  4. 给potplayer配置iptv源,看所有你想看的电视
  5. POJ 博弈论
  6. Maven多模块Spring的注入
  7. CentOS下 Django部署 uWSGI+Django(一)
  8. npm 报错 : npm ERR! Maximum call stack size exceeded
  9. 第二十一篇 -- QTimer实现秒表功能
  10. Git常用命令和基础使用