spring security 3 扩展 HttpSessionEventPublisher 统计在线用户数

   1. package com.hp.ts.bca.security.online;  
   2.   
   3. import javax.servlet.http.HttpSessionEvent;  
   4.   
   5. import org.springframework.security.Authentication;  
   6. import org.springframework.security.context.SecurityContextHolder;  
   7. import org.springframework.security.ui.session.HttpSessionEventPublisher;  
   8. import org.springframework.web.context.WebApplicationContext;  
   9. import org.springframework.web.context.support.WebApplicationContextUtils;  
  10.   
  11. import com.yourcompany.domain.entity.security.User;  
  12. import com.yourcompany.service.mgmt.OnlineUserService;  
  13.   
  14. /** 
  15.  * 扩展的HttpSessionEventPublisher 
  16.  * 支持在线人数统计 
  17.  * 
  18.  */  
  19. public class EnhancedHttpSessionEventPublisher extends HttpSessionEventPublisher {  
  20.   
  21.     @Override  
  22.     public void sessionCreated(HttpSessionEvent event) {  
  23.         // 将用户加入到在线用户列表中  
  24.         saveOrDeleteOnlineUser(event, Type.SAVE);  
  25.         super.sessionCreated(event);  
  26.     }  
  27.   
  28.     @Override  
  29.     public void sessionDestroyed(HttpSessionEvent event) {  
  30.         // 将用户从在线用户列表中移除  
  31.         saveOrDeleteOnlineUser(event, Type.DELETE);  
  32.         super.sessionDestroyed(event);  
  33.     }  
  34.   
  35.     public void saveOrDeleteOnlineUser(HttpSessionEvent event, Type type) {  
  36.         Authentication auth = SecurityContextHolder.getContext().getAuthentication();  
  37.         if (auth != null) {  
  38.             Object principal = auth.getPrincipal();  
  39.             if (principal instanceof User) {  
  40.                 User user = (User) principal;  
  41.                
  44.                 switch (type) {  
  45.                 case SAVE:  
  46.                     OnlineUserList.add(user.getId);//List<String> 
  47.                     break;  
  48.                 case DELETE:  
  49.                     OnlineUserList.remove(user.getId);
  50.                     break;  
  51.                 }  
  52.             }  
  53.         }  
  54.     }  
  55.   
  56.     /** 
  57.      * 定义一个简单的内部枚举 
  58.      */  
  59.     private static enum Type {  
  60.         SAVE, DELETE;  
  61.     }  
  62.   
  63. }  

 web.xml 里的配置

 <listener>  
	     <listener-class>
com.hp.ts.bca.security.online.EnhancedHttpSessionEventPublisher  
	     </listener-class>  
	 </listener>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值