request.getSession(true)和request.getSession(false)的區別


request.getSession(true):若存在會話則返回該會話,否則新建一個會話。

request.getSession(false):若存在會話則返回該會話,否則返回NULL。

三種重載方法

現實中我們經常會遇到以下3種用法:

HttpSession session = request.getSession();
HttpSession session = request.getSession(true);
HttpSession session = request.getSession(false);

三種重載方法的區別

Servlet官方文檔的說明:

public HttpSessiongetSession(boolean create) 

Returns the currentHttpSession associated with this request or, if if there is no current sessionand create is true, returns a new session. 
If create is falseand the request has no valid HttpSession, this method returns null. 
To make sure thesession is properly maintained, you must call this method before the responseis committed. If the container is using cookies to maintain session integrityand is asked to create a new session when the response is committed, anIllegalStateException is thrown. 
Parameters: true -to create a new session for this request if necessary; false to return null if there's no current session.
Returns: theHttpSession associated with this request or null if create is false and therequest has no valid session.

翻譯過來的意思就是:getSession(boolean create)是返回當前reqeust中的HttpSession ,如果當前reqeust中的HttpSession為null,當create為true,就創建一個新的Session;當create為false,則返回null。create的默認值為true,即這里的HttpServletRequest.getSession(ture)等同於HttpServletRequest.getSession()。

根據這個特性,在使用上,當向Session中存取登錄信息時,一般建議使用request.getSession()/request.getSession(true);當從Session中只獲取登錄信息時,一般建議使用request.getSession(false)。

當然了,現在各種Web框架都會封裝一些方便存取Session的工具類,一般是不建議直接從request中獲取Session或前台參數什么的。

 

"不要輕易把傷口揭開給別人看,因為別人看的是熱鬧,而痛的卻是自己。"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM