JAVA开发示例:用户登录成功后重新设置Session

问题描述

img

示例代码

HttpSession session = request.getSession();

// 用来存储原sessionde的值
ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap();

Enumeration enumeration = session.getAttributeNames();
// 遍历enumeration
while (enumeration.hasMoreElements()) {
  // 获取session的属性名称
  String name = enumeration.nextElement().toString();
  // 根据键值取session中的值
  concurrentHashMap.put(name,session.getAttribute(name));
}

// 获取之前旧的session
HttpSession oldSession = request.getSession(false);
if (oldSession != null) {
  //废除掉登陆前的session
  oldSession.invalidate();
}
request.getSession(true);
// 获取新session
session = request.getSession();
// 将原先老session的值存入
Iterator<Map.Entry<String, String>> it = concurrentHashMap.entrySet().iterator();
while (it.hasNext()) {
  Map.Entry<String, String> entry = it.next();
  session.setAttribute(entry.getKey(), entry.getValue());
}

参考资料

https://www.cnblogs.com/csnjava/p/14638240.html

posted on 2022-03-23 16:15  白首码农  阅读(628)  评论(0编辑  收藏  举报