The difference between request and getSession of true false and null

  • 2020-06-07 04:35:57
  • OfStack

The difference between ES2en. getSession(true/false/null) in java

1. Demand reasons

In real life, we often encounter the following three usages:

HttpSession session = request.getSession();

HttpSession session = request.getSession(true);

HttpSession session = request.getSession(false);

2. The difference between

1. The official document of Servlet says:

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. Translation:

getSession(boolean create) means to return HttpSession in the current reqeust, if HttpSession in the current reqeust is null, when create is true, create a new Session, otherwise return null;

In short:

HttpServletRequest.getSession(ture) Is equivalent to  HttpServletRequest.getSession() 
HttpServletRequest.getSession(false) Is equivalent to   If the current Session Not just for null ;  

Use 3.

When accessing login information to Session, 1 general advice: HttpSession session = ES66en.getSession ();

When getting login information from Session, 1 general recommendation: HttpSession session = request. getSession(false);

4. A simpler approach

If you are using Spring in your project, it is much easier to use session. If you need in Session values, can use WebUtils tools (org. springframework. web. util. WebUtils) WebUtils. getSessionAttribute (HttpServletRequestrequest, String name); Method, look at 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 != null ? session.getAttribute(name) : null); 


Note: Assert is one of the tools in the Spring toolkit that is used to determine whether a validation operation, in this case reqeust, is null and to throw an exception if it is

When you use:

WebUtils.setSessionAttribute(request, "user", User);

User user = (User)WebUtils.getSessionAttribute(request, "user");

Thank you for reading, I hope to help you, thank you for your support to this site!

Related articles: