在我登陸成功以後,我會java
session.setAttribute("user", userMap);//設置session
因此就寫了一個監聽器來控制登陸的。web
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裏配置監聽器session
<listener> <listener-class>org.system.utils.OnlineUserListener</listener-class> </listener>