request.getSession() ture/false

出處:http://blog.csdn.net/xxd851116/archive/2009/06/25/4296866.aspx

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");
}
發佈了44 篇原創文章 · 獲贊 1 · 訪問量 3091
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章