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 }
View Code

2:添加监听: 

1 <listener>
2 <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
3 </listener>
View Code

 

posted @ 2021-03-25 22:57  现在开始JAVA  阅读(51)  评论(0)    收藏  举报