java 中 request.getSession(true、false、null)的區(qū)別
java 中 request.getSession(true/false/null)的區(qū)別
一、需求原因
現(xiàn)實中我們經(jīng)常會遇到以下3中用法:
HttpSession session = request.getSession();
HttpSession session = request.getSession(true);
HttpSession session = request.getSession(false);
二、區(qū)別
1. 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 ifthere's no current session
Returns: theHttpSession associated with this request or null if create is false and therequest has no valid session
2. 翻譯過來的意思是:
getSession(boolean create)意思是返回當前reqeust中的HttpSession ,如果當前reqeust中的HttpSession 為null,當create為true,就創(chuàng)建一個新的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)的WebUtils.getSessionAttribute(HttpServletRequestrequest, String name);方法,看看源碼:
public static 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");
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
SpringBoot使用@Validated處理校驗的方法步驟
@Validated?注解的主要目的是啟用和利用?Spring?的驗證框架,它可以用于類上也可以用于方法參數(shù)上,本文給大家介紹了SpringBoot使用@Validated優(yōu)雅的處理校驗的方法步驟,通過代碼示例介紹的非常詳細,需要的朋友可以參考下2024-08-08
Java使用Runnable和Callable實現(xiàn)多線程的區(qū)別詳解
這篇文章主要為大家詳細介紹了Java使用Runnable和Callable實現(xiàn)多線程的區(qū)別之處,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下2022-07-07
使用通過ARP類似P2P終結者實現(xiàn)數(shù)據(jù)封包
目前網(wǎng)絡上類似P2P終結者這類軟件,主要都是基于ARP欺騙實現(xiàn)的,網(wǎng)絡上到處都有關于ARP的介紹,不過為了本文讀者不需要再去查找,我就在這里大概講解一下2012-12-12
java讀取配置文件(properties)的時候,unicode碼轉utf-8方式
這篇文章主要介紹了java讀取配置文件(properties)的時候,unicode碼轉utf-8方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02

