java 中 request.getSession(true/false/null)的區(qū)別
一、需求原因
現(xiàn)實(shí)中我們經(jīng)常會(huì)遇到以下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)意思是返回當(dāng)前reqeust中的HttpSession ,如果當(dāng)前reqeust中的HttpSession 為null,當(dāng)create為true,就創(chuàng)建一個(gè)新的Session,否則返回null;
簡而言之:
1
2
|
HttpServletRequest.getSession(ture)等同于 HttpServletRequest.getSession() HttpServletRequest.getSession( false )等同于 如果當(dāng)前Session沒有就為 null ; |
3. 使用
當(dāng)向Session中存取登錄信息時(shí),一般建議:HttpSession session =request.getSession();
當(dāng)從Session中獲取登錄信息時(shí),一般建議:HttpSession session =request.getSession(false);
4. 更簡潔的方式
如果你的項(xiàng)目中使用到了Spring,對session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的WebUtils.getSessionAttribute(HttpServletRequestrequest, String name);方法,看看源碼:
1
2
3
4
5
6
7
8
9
|
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工具包中的一個(gè)工具,用來判斷一些驗(yàn)證操作,本例中用來判斷reqeust是否為空,若為空就拋異常
你使用時(shí):
1
2
3
4
|
WebUtils.setSessionAttribute(request, "user" , User); User user = (User)WebUtils.getSessionAttribute(request, "user" ); <br> |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:https://my.oschina.net/anxiaole/blog/840890