session监听器
课程代码:
1:实现监听接口:
1 public class OnlineCountListener implements HttpSessionListener { 2 3 public void sessionCreated(HttpSessionEvent se) { 4 ServletContext ctx = se.getSession().getServletContext(); 5 6 System.out.println(se.getSession().getId()); 7 8 Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); 9 10 if(onlineCount == null){ 11 onlineCount = new Integer(1); 12 }else{ 13 int count = onlineCount.intValue(); 14 15 onlineCount += 1; 16 } 17 18 ctx.setAttribute("OnlineCount",onlineCount); 19 } 20 21 public void sessionDestroyed(HttpSessionEvent se) { 22 ServletContext ctx = se.getSession().getServletContext(); 23 Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); 24 25 if(onlineCount == null){ 26 onlineCount = new Integer(0); 27 }else{ 28 int count = onlineCount.intValue(); 29 30 onlineCount -=1; 31 } 32 33 ctx.setAttribute("OnlineCount",onlineCount); 34 } 35 }
2:添加监听:
1 <listener> 2 <listener-class>com.kuang.listener.OnlineCountListener</listener-class> 3 </listener>

浙公网安备 33010602011771号