我已经制定了当第二个用户成功登录时删除第一个用户会话的逻辑。
这里是配置
@WebListener
public class SessionConfig implements HttpSessionListener {
private static final Map<String, HttpSession> sessions = new ConcurrentHashMap<>();
public synchronized static String getSessionIdCheck(String type, String compareId) {
String result = "";
for(String key : sessions.keySet()) {
HttpSession hs = sessions.get(key);
if(hs != null && hs.getAttribute(type) != null && hs.getAttribute(type).toString().equals(compareId)) {
result = key.toString();
}
}
removeSessionForDoubleLogin(result);
return result;
}
private static void removeSessionForDoubleLogin(String userId) {
System.out.println("=========== remove userId : " + userId + " ===========");
if(userId != null && userId.length() > 0) {
sessions.get(userId).invalidate();
sessions.remove(userId);
}
}
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("=========== sessionCreated : " + se + " =========== ");
sessions.put(se.getSession().getId(), se.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
if(sessions.get(se.getSession().getId()) != null){
sessions.get(se.getSession().getId()).invalidate();
sessions.remove(se.getSession().getId());
}
}
}
这里是控制器
if(userId != null){
String sessionChkUserId = SessionConfig.getSessionIdCheck("login_id", userId);
System.out.println(userId + " : " + sessionChkUserId);
session.setMaxInactiveInterval(60 * 60);
session.setAttribute("login_id", userId);
}
在这种情况下,删除第一个用户的会话并注销也回到登录页面。 第二个用户可以连接网站。
但是当第二个用户登录时,我无法开发为第一个用户显示警报。
我该怎么做?
登录的时候使用websocket做回话连接,当第二个登录的时候,通过websocket发送一个消息推送