J2EE很基礎的東西,記下來。 :shock:
getSession(boolean create)意思是返回當前reqeust中的HttpSession ,如果當前reqeust中的HttpSession 爲null,當create爲true,就創建一個新的Session,否則返回null;
簡而言之:
HttpServletRequest.getSession(ture) 等同於ttpServletRequest.getSession()
HttpServletRequest.getSession(false) 等同於 如果當前Session沒有就爲null;
【問題和bug】:
我周圍很多同事是這樣寫的;
view plaincopy to clipboardprint?
HttpSession session = request.getSession(); // a new session created if no session exists, 哈哈!完蛋啦!如果session不存在的話你又創建了一個!
String user_name = session.getAttribute("user_name");
[code="java"]
需要注意的地方是request.getSession() 等同於 request.getSession(true),除非我們確認session一定存在或者sesson不存在時明確有創建session的需要,否則儘量使用request.getSession(false)。在使用request.getSession()函數,通常在action中檢查是否有某個變量/標記存放在session中。這個場景中可能出現沒有session存在的情況,正常的判斷應該是這樣:
[code="java"]
view plaincopy to clipboardprint?
HttpSession session = request.getSession(false);
if (session != null) {
String user_name = session.getAttribute("user_name");
}