监听器利用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>
道阻且长,行则将至