`
清晨阳光
  • 浏览: 39023 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

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
4
分享到:
评论
2 楼 ybjz 2013-09-09  
OnlineUserService 这个service 是做什么的,看不懂哦
1 楼 sslining 2013-06-21  
你好,我想请问一下,基于spring security 3.1 如何去操作,获得所有登陆在线的用户

相关推荐

Global site tag (gtag.js) - Google Analytics