在網上常常看到有人對request.getSession(false)提出疑問,我第一次也很迷惑,看了一下J2EE1.3 API,看一下官網是怎麼解釋的。 html
【官方解釋】java
getSession web
public HttpSession getSession(boolean create)spring
Returns the current HttpSession
associated with this request or, if if there is no current session and create
is true, returns a new session.cookie
If create
is false
and the request has no valid HttpSession
, this method returns null
.session
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.app
Parameters:
- to create a new session for this request if necessary; true
false
to return null
if there's no current sessionide
Returns: the HttpSession
associated with this request or null
if create
is false
and the request has no valid session函數
譯:工具
getSession(boolean create)意思是返回當前reqeust中的HttpSession ,若是當前reqeust中的HttpSession 爲null,當create爲true,就建立一個新的Session,不然返回null;
簡而言之:
HttpServletRequest.getSession(ture) 等同於 HttpServletRequest.getSession()
HttpServletRequest.getSession(false) 等同於 若是當前Session沒有就爲null;
【問題和bug】:
我周圍不少同事是這樣寫的;
須要注意的地方是request.getSession() 等同於 request.getSession(true),除非咱們確認session必定存在或者sesson不存在時明確有建立session的須要,不然儘可能使用request.getSession(false)。在使用request.getSession()函數,一般在action中檢查是否有某個變量/標記存放在session中。這個場景中可能出現沒有session存在的狀況,正常的判斷應該是這樣:
【投機取巧】:
若是項目中用到了Spring(其實只要是Java的稍大的項目,Spring是一個很好的選擇),對session的操做就方便多了。若是須要在Session中取值,能夠用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequest request, String name)方法,看看高手寫的源碼吧:哈哈。。
注:Assert是Spring工具包中的一個工具,用來判斷一些驗證操做,本例中用來判斷reqeust是否爲空,若爲空就拋異常。
上面的代碼又能夠簡潔一下啦,看吧: