强制更新JsessionID的方法


登录前的请求一般都是http的,http是不安全的,假设用户登录前的JSESSIONID被人取得,如果登录后不变更JSESSIONID的话,即使登录请求是https的,该用户仍然会被他人冒充。

/** 
 * 重置sessionid,原session中的数据自动转存到新session中 
 * @param request 
 */  
public static void reGenerateSessionId(HttpServletRequest request){  
      
    HttpSession session = request.getSession();  
      
    //首先将原session中的数据转移至一临时map中  
    Map<String,Object> tempMap = new HashMap();  
    Enumeration<String> sessionNames = session.getAttributeNames();  
    while(sessionNames.hasMoreElements()){  
        String sessionName = sessionNames.nextElement();  
        tempMap.put(sessionName, session.getAttribute(sessionName));  
    }  
      
    //注销原session,为的是重置sessionId  
    session.invalidate();  
      
    //将临时map中的数据转移至新session  
    session = request.getSession();  
    for(Map.Entry<String, Object> entry : tempMap.entrySet()){  
        session.setAttribute(entry.getKey(), entry.getValue());  
    }  
} 





原文地址:https://www.cnblogs.com/DiZhang/p/12545112.html