English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java request.getSession(true/false/The difference between (null)
I. Reason for the requirement
In reality, we often encounter the following3Usage in:
HttpSession session = request.getSession();
HttpSession session = request.getSession(true);
HttpSession session = request.getSession(false);
II. Differences
1. The official Servlet documentation states:
public HttpSession getSession(boolean create)
Returns the currentHttpSession associated with this request or, 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 ensure that 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 therequest has no valid session
2. The translation means:
The meaning of getSession(boolean create) is to return the HttpSession associated with the current request. If the HttpSession associated with the current request is null, and create is true, a new Session will be created; otherwise, null will be returned.
In short:
HttpServletRequest.getSession(true) is equivalent to HttpServletRequest.getSession(); HttpServletRequest.getSession(false) is equivalent to if the current Session does not exist, it returns null;
3. Use
When accessing login information in the Session, it is generally recommended: HttpSession session = request.getSession();
When getting login information from the Session, it is generally recommended: HttpSession session =request.getSession(false);
4. A more concise way
If your project uses Spring, the operation of session becomes much easier. If you need to get a value from the Session, you can use the WebUtils utility (org.springframework.web.util.WebUtils) method WebUtils.getSessionAttribute(HttpServletRequestrequest, String name);, see the source code:
public static Object getSessionAttribute(HttpServletRequest request, String name){ Assert.notNull(request, "Request must not be null"); HttpSession session = request.getSession(false); return (session != null63; session.getAttribute(name) : null); {}
Note: Assert is a tool in the Spring framework, used to judge some validation operations, in this example, it is used to judge whether reqeust is empty, and if it is empty, an exception is thrown
When you use it:
WebUtils.setSessionAttribute(request, "user", User); User user = (User)WebUtils.getSessionAttribute(request, "user");
Thank you for reading, hoping to help everyone, thank you for your support to this site!