spring security为了防止固定回话攻击会一直修改sessionId,所以在登录前存在session里的数据在登录后是获取不到的。为了解决这种情况可以监听session的变化做相应的更改。
@WebListener public class SessionListener implements HttpSessionListener, HttpSessionIdListener { @Override public void sessionCreated(HttpSessionEvent se) { StaticSessionContext.addSession(se.getSession()); } @Override public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); StaticSessionContext.removeSession(session); } // 在改方法中可以将原来session的数据移到新的session中 @Override public void sessionIdChanged(HttpSessionEvent httpSessionEvent, String oldSessionId) { HttpSession oldSession = StaticSessionContext.getSession(oldSessionId); if(oldSession != null) { StaticSessionContext.removeSession(oldSession); } StaticSessionContext.addSession(httpSessionEvent.getSession()); } }
public class StaticSessionContext { private static ConcurrentMap<String, HttpSession> attributes = new ConcurrentHashMap(); private StaticSessionContext() { } public static void addSession(HttpSession session) { if(session != null) { System.err.println(session.getId()); attributes.put(session.getId(), session); } } public static void removeSession(HttpSession session) { if(session != null) { attributes.remove(session.getId()); } } public static HttpSession getSession(String sessionId) { if(sessionId == null) { return null; } return attributes.get(sessionId); } }
参考地址:https://blog.csdn.net/qq_36500178/article/details/113091776