Difference between request.getSession() and request.getSession(true)

后端 未结 7 1734
难免孤独
难免孤独 2021-01-31 08:43

I understand the difference between request.getSession(true) and request.getSession(false). But request.getSession() & request.g

相关标签:
7条回答
  • 2021-01-31 09:02

    request.getSession() will return a current session. if current session does not exist, then it will create a new one.

    request.getSession(true) will return current session. If current session does not exist, then it will create a new session.

    So basically there is not difference between both method.

    request.getSession(false) will return current session if current session exists. If not, it will not create a new session.

    0 讨论(0)
  • 2021-01-31 09:02

    They both return the same thing, as noted in the documentation you linked; an HttpSession object.

    You can also look at a concrete implementation (e.g. Tomcat) and see what it's actually doing: Request.java class. In this case, basically they both call:

    Session session = doGetSession(true);
    
    0 讨论(0)
  • 2021-01-31 09:04

    Method with boolean argument :

      request.getSession(true);
    

    returns new session, if the session is not associated with the request

      request.getSession(false);
    

    returns null, if the session is not associated with the request.

    Method without boolean argument :

      request.getSession();
    

    returns new session, if the session is not associated with the request and returns the existing session, if the session is associated with the request.It won't return null.

    0 讨论(0)
  • 2021-01-31 09:04

    A major practical difference is its use:

    in security scenario where we always needed a new session, we should use request.getSession(true).

    request.getSession(false): will return null if no session found.
    
    0 讨论(0)
  • 2021-01-31 09:04

    request.getSession() or request.getSession(true) both will return a current session only . if current session will not exist then it will create a new session.

    0 讨论(0)
  • 2021-01-31 09:08

    request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

    0 讨论(0)
提交回复
热议问题