Check valid session: isRequestedSessionIdValid () vs getSession (false)

I am developing Java Servlets. When you check if the user is registered, I want to check if the HTTP request has a valid session. To test this, I have 2 options:

(1)

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) { // user is logged in ... } } 

Since I pass false as an argument, a new session is not created if there is no longer a valid session, and the function returns null, which I can check.

Or me:

(2)

  if (request.isRequestedSessionIdValid()) { // user is logged in ... } 

Is there any difference, any advantage / disadvantage? Or are both functions more or less the same?

+6
source share
2 answers

Javadoc Form

isRequestedSessionIdValid boolean isRequestedSessionIdValid () Checks whether the requested session identifier is valid. If the client did not specify a session identifier, this method returns false.

Returns: true if this request has an identifier for a valid session in the current session context; false otherwise

So, in the sense, they are both the same. But what you need to know is request.getSession (false) will be null only in case of the first request for the container. After the first request container creates a session and sends a Jsessionid cookie along with the response, it can track subsequent requests from the same browser. Therefore, in your case, instead of checking whether the session is null or not, you should save the session attribute "is_logged_in" = true and check this attribute if the session is not equal to zero.

+10
source

Based on the JavaDoc wording, it would seem that there would be a difference: if a valid session was already created (from the previous call to request.getSession(true) ), then the requested session identifier would be invalid, but request.getSession(false) would return a valid (not null) session. I have not tested this theory.

+1
source

All Articles