监听器利用Session统计网站在线人数
转载
监听器
统计网站在线人数
package com.ding.listener;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* @Description 统计在线人数
* @Author 丁帅帅
* @Date 21/08/11 15:07
* @Version 1.0
*/
@WebListener
public class OnlineListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent Event) {
ServletContext context =Event.getSession().getServletContext();
// System.out.println(Event.getSession().getId());
Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount =new Integer(1);
}else{
//int count = onlineCount.intValue();
onlineCount = onlineCount + 1;
}
context.setAttribute("OnlineCount", onlineCount);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
ServletContext context = event.getSession().getServletContext();
Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
if (onlineCount == null) {
onlineCount = new Integer(0);
} else {
int count = onlineCount.intValue();
onlineCount = count - 1;
}
context.setAttribute("OnlineCount", onlineCount);
}
}
<%--
User: 丁帅帅
Date: 21/08/11
Time: 15:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>在线人数</title>
</head>
<body>
<h1>当前有 <span style="color: blue">
${OnlineCount}</span>
人在线</h1>
</body>
</html>
世界不会因为你的疲惫,而停下它的脚步
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。