request.getSession()和request.getSession(true)意思相同:獲取session,如果session不存在,就新建一個
reqeust.getSession(false)獲取session,如果session不存在,則返回null
如果 項目中無法確定回話一定存在,最好用request.session(false);
getSession(boolean create)意思是返回當前reqeust中的HttpSession ,如果當前reqeust中的HttpSession 為null,當create為true,就創建一個新的Session,否則返回null;
簡而言之:
HttpServletRequest.getSession(ture)等同於 HttpServletRequest.getSession()
HttpServletRequest.getSession(false)等同於 如果當前Session沒有就為null;
3. 使用
當向Session中存取登錄信息時,一般建議:HttpSession session =request.getSession();
當從Session中獲取登錄信息時,一般建議:HttpSession session =request.getSession(false);
4. 更簡潔的方式
如果你的項目中使用到了spring(當然大點的項目都用到了),對session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequestrequest, String name)方法,看看源碼:
publicstatic Object getSessionAttribute(HttpServletRequest request, String name){
Assert.notNull(request, "Request must not be null");
HttpSession session =request.getSession(false);
return (session != null ?session.getAttribute(name) : null);
}
注:Assert是Spring工具包中的一個工具,用來判斷一些驗證操作,本例中用來判斷reqeust是否為空,若為空就拋異常
你使用時:WebUtils.setSessionAttribute(request, “user”, User);
User user = (User)WebUtils.getSessionAttribute(request, “user”);
三、運行結果
以上例子均測試驗證通過。