session唯一登录用户

本文介绍了一种基于HTTPSession的用户登录与注销机制实现方法,包括如何处理用户的登录状态更新和注销操作,以及如何监听在线用户数量的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

页面跳转时才会退出,要主动退出,需要js的定时心跳包

 

	//userid=httpsession
	public static Map<Integer, HttpSession> USERID_SESSIONS = new ConcurrentHashMap<Integer, HttpSession>();
	

 

 

	public static void addLoginUser(HttpServletRequest request,Map<String, Object> user){
		//退出之前的session
		int id = StringUtil.toInt(user.get("id"));
		if (id>0) {
			HttpSession session_old = ChipmunkCache.USERID_SESSIONS.get(id);
			if (session_old!=null) {
				ChipmunkCache.USERID_SESSIONS.remove(id);
				System.out.println("old sessionid:"+session_old.getId());
				System.out.println(session_old.isNew());
				session_old.removeAttribute(SESSION_USER);
				session_old.invalidate();//销毁session,会调用HttpSessionListener的sessionDestroyed
			}
			HttpSession session_new = request.getSession();
			System.out.println("new sessionid:"+session_new.getId());
			session_new.setAttribute(SESSION_USER, user);
			ChipmunkCache.USERID_SESSIONS.put(id, session_new);
		}
		//add(request, SESSION_USER, user);
	}

	public static void removeLoginUser(HttpServletRequest request){
		HttpSession session = request.getSession();
		Map<String, Object> user = getLoginUser(session);
		if (user!=null) {
			int id = StringUtil.toInt(user.get("id")); 
			ChipmunkCache.USERID_SESSIONS.remove(id);
		}
		session.removeAttribute(SESSION_USER);
		//重置sessionid,防漏洞
		try {
			session.invalidate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

 

public class MySessionListener implements HttpSessionListener{
	
	private static AtomicInteger online_count = new AtomicInteger(0);
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		int count = online_count.incrementAndGet();
		System.out.println("online count:"+count);
		HttpSession session = event.getSession();
//		online_user_map.put(session.getId(), value)
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		int count = online_count.decrementAndGet();
		System.out.println("online count:"+count);
		
	}
	
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值