Check for valid session: isRequestedSessionIdValid

2019-04-28 08:38发布

I'm developing Java Servlets. At the point of checking whether a user is logged in, I want to check if the HTTP request has a valid session. For checking that, I have 2 possibilities:

(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, there is no new session created if there is no valid session existing already, and the function returns null, for what I can check.

Or I do:

(2)

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

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

2条回答
家丑人穷心不美
2楼-- · 2019-04-28 08:44

Form Javadoc

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

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

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

查看更多
疯言疯语
3楼-- · 2019-04-28 08:56

Based on the wording of the JavaDoc, it seems like there would be a distinction: if a valid session has already been created (from a prior call to request.getSession(true)), then the requested session ID will not be valid, but request.getSession(false) will have a valid (non-null) session to return. I haven't tested this theory.

查看更多
登录 后发表回答