监听器
实现一个监听器的接口;
1. 编写一个监听器
实现监听器的接口
public class OnlineCountListener implements HttpSessionListener { //创建Session监听:看你的一举一动 //一旦创建Session就会触发一次这个事件 public void sessionCreated(HttpSessionEvent httpSessionEvent) { ServletContext sc = httpSessionEvent.getSession().getServletContext(); Integer oc = (Integer) sc.getAttribute("OnlineCount"); if(oc==null){ oc = new Integer(1); }else{ int count =oc.intValue(); oc = new Integer(count+1); } sc.setAttribute("OnlineCount",oc); } //销毁Session监听 //一旦销毁Session就会触发一次这个事件 public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { ServletContext sc = httpSessionEvent.getSession().getServletContext(); Integer oc = (Integer) sc.getAttribute("OnlineCount"); if(oc==null){ oc = new Integer(0); }else{ int count =oc.intValue(); oc = new Integer(count-1); } sc.setAttribute("OnlineCount",oc); /* Session销毁的方案 1.手动销毁 2.自动销毁 */ } }
- web.xml中注册监听器
<!-- 注册监听器--> <listener> <listener-class>com.kuang.listener.OnlineCountListener</listener-class> </listener>