8.监听器Listener
实现一个监听器的接口;(有n种监听器)
统计网站人数demo(统计session)
package com.lxw.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineCountListener implements HttpSessionListener {
//创建session的监听
//一旦创建session,就会触发一次这个事件
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println("SessionID=" + se.getSession().getId());
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = 1;
}else{
onlineCount++;
}
ctx.setAttribute("OnlineCount",onlineCount);
}
//销毁session的监听
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
// se.getSession().invalidate();//手动销毁session
if (onlineCount==null){
onlineCount = 0;
}else{
onlineCount--;
}
ctx.setAttribute("OnlineCount",onlineCount);
}
}
web.xml中注册监听器
<!-- 注册监听器-->
<listener>
<listener-class>com.lxw.listener.OnlineCountListener</listener-class>
</listener>
评论区