1、创建监听器,实现监听器接口
package com.lyh.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数,统计看session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听,看你的一举一动
//一旦创建session就会触发一次事件
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext context = httpSessionEvent.getSession().getServletContext();
System.out.println(httpSessionEvent.getSession().getId());
Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount=new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount=new Integer(count+1);
}
context.setAttribute("OnlineCount",onlineCount);
}
//销毁session监听
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext context = httpSessionEvent.getSession().getServletContext();
System.out.println(httpSessionEvent.getSession().getId());
Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount=new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount=new Integer(count-1);
}
context.setAttribute("OnlineCount",onlineCount);
}
}
2、在web.xml中注册监听器
<!-- 监听器配置-->
<listener>
<listener-class>com.lyh.listener.OnlineCountListener</listener-class>
</listener>
3、看着使用
标签:监听器,httpSessionEvent,十二,listener,session,context,Integer,onlineCount From: https://www.cnblogs.com/lyhidea/p/16950482.html