session 控制单点登录
在我登录成功之后,我会
session.setAttribute("user", userMap);//设置session
所以就写了一个监听器来控制登录的。
package org.system.utils; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class OnlineUserListener implements HttpSessionAttributeListener { private final static ConcurrentHashMap<Integer, HttpSession> onlineMap = new ConcurrentHashMap<>(); @Override public void attributeAdded(HttpSessionBindingEvent event) { /* 获取session里面的用户信息 */ @SuppressWarnings("unchecked") Map<String, Object> userMap = (Map<String, Object>) event.getSession().getAttribute("user"); int userId = (int) userMap.get("id"); if (onlineMap.containsKey(userId)) { onlineMap.get(userId).invalidate(); } onlineMap.put(userId, event.getSession()); HttpSessionAttributeListener.super.attributeAdded(event); } }
在web.xml里配置监听器
<listener> <listener-class>org.system.utils.OnlineUserListener</listener-class> </listener>
每件事都需要坚持!