Spring Security统计在线用户

在web.xml中将原先的那个监听器替换为自己写的这个就可以了,检测在线用户的只有一个表,里面只有一个id字段。如果用户不是很多,这个表可以是一个MySQL的内存表,或者Oralce的表存储修改为内存。

package com.yourcompany.service.security;

import javax.servlet.http.HttpSessionEvent;

import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.ui.session.HttpSessionEventPublisher;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yourcompany.domain.entity.security.User;
import com.yourcompany.service.mgmt.OnlineUserService;

/**
 * 扩展的HttpSessionEventPublisher
 * 支持在线人数统计
 *
 */
public class EnhancedHttpSessionEventPublisher extends HttpSessionEventPublisher {

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		// 将用户加入到在线用户列表中
		saveOrDeleteOnlineUser(event, Type.SAVE);
		super.sessionCreated(event);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		// 将用户从在线用户列表中移除
		saveOrDeleteOnlineUser(event, Type.DELETE);
		super.sessionDestroyed(event);
	}

	public void saveOrDeleteOnlineUser(HttpSessionEvent event, Type type) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null) {
			Object principal = auth.getPrincipal();
			if (principal instanceof User) {
				User user = (User) principal;
				WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(event
						.getSession().getServletContext());
				OnlineUserService onlineUserService = (OnlineUserService) wac.getBean("onlineUserService");
				switch (type) {
				case SAVE:
					onlineUserService.saveOnlineUser(user.getId());
					break;
				case DELETE:
					onlineUserService.deleteOnlineUser(user.getId());
					break;
				}
			}
		}
	}

	/**
	 * 定义一个简单的内部枚举
	 */
	private static enum Type {
		SAVE, DELETE;
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值