http://blog.csdn.net/gaolinwu/article/details/7285783
About the difference between request.getsession (True/false/null)
First, the cause of demand
In reality we often encounter the following 3 usage:
HttpSession session = Request.getsession ();
HttpSession session = Request.getsession (true);
HttpSession session = Request.getsession (false);
Second, the difference
1. The official servlet document says:
Public Httpsessiongetsession (Boolean create)
Returns the currenthttpsession associated with this request or, if if there are no current Sessionand Create is true, retur NS a new session.
IF Create is Falseand the request have no valid HttpSession, this method returns NULL.
To make sure thesession are properly maintained, you must call this method before the Responseis committed. If the container is using the cookie to maintain session Integrityand was asked to create a new session then the response is C Ommitted, 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 have no valid session
2. The translation comes to mean:
GetSession (Boolean create) means to return the httpsession in the current reqeust if httpsession in the current reqeust is null, and when Create is true, a new session is created , otherwise null is returned;
Nutshell:
Httpservletrequest.getsession (ture) is equivalent to Httpservletrequest.getsession ()
Httpservletrequest.getsession (False) is equivalent to NULL if the current session is not present;
3. Use
When accessing login information to the session, General recommendation: HttpSession session =request.getsession ();
When obtaining login information from the session, general recommendation: HttpSession session =request.getsession (FALSE);
4. A more concise approach
If you have a project that uses spring (and of course the larger items are used), the session is much easier to do. If you need to take a value in session, you can use the Webutils tool (Org.springframework.web.util.WebUtils) Getsessionattribute ( Httpservletrequestrequest, String name) method, look at the source code:
Publicstatic Object Getsessionattribute (httpservletrequest request, String name) {
Assert.notnull (Request, "request must not is null");
HttpSession session =request.getsession (FALSE);
Return (Session! = null? Session.getattribute (name): null);
}
Note: Assert is a tool in the Spring Toolkit that is used to determine some validation actions, in this case, to determine if the reqeust is empty and throw an exception if it is empty
When you use: Webutils.setsessionattribute (Request, "user", user);
User user = (user) Webutils.getsessionattribute (request, "user");
Iii. Results of operation
The above examples are tested and validated.
The difference between "turn" and "Request.getsession" (true/false/null)