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>