【前面的話】
在網上經常看到有人對request.getSession(false)提出疑問,我第一次也很迷惑,看了一下J2EE1.3 API,看一下官網是怎么解釋的。
【官方解釋】
getSession
public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
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.
Parameters: true - to create a new session for this request if necessary; false to return null if there's no current session
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】:
我周圍很多同事是這樣寫的;
復制代碼 代碼如下:
HttpSession session = request.getSession(); // a new session created if no session exists, 哈哈!完蛋啦!如果session不存在的話你又創建了一個!
String user_name = session.getAttribute("user_name");
復制代碼 代碼如下:
HttpSession session = request.getSession(false);
if (session != null) {
String user_name = session.getAttribute("user_name");
}
復制代碼 代碼如下:
/**
* Check the given request for a session attribute of the given name.
* Returns null if there is no session or if the session has no such attribute.
* Does not create a new session if none has existed before!
* @param request current HTTP request
* @param name the name of the session attribute
* @return the value of the session attribute, or <code>null</code> if not found
*/
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);
}
復制代碼 代碼如下:
HttpSession session = request.getSession(false);
String user_name = WebUtils.getSessionAttribute(reqeust, "user_name");
|
新聞熱點
疑難解答