1. Overview

In this quick tutorial, we’ll see the difference between calling *HttpServletRequest#*getSession() and *HttpServletRequest#*getSession(boolean).

2. What’s the Difference?

The methods getSession() and getSession(boolean) are very similar. There’s a small difference, though. The difference is whether the session should be created if it doesn’t exist already.

Calling getSession() and getSession(true) are functionally the same: retrieve the current session, and if one doesn’t exist yet, create it.

Calling getSession(false), though, retrieves the current session, and if one doesn’t exist yet, returns null. Among other things, this is handy when we want to ask if the session exists.

3. Example

In this example, we are considering this scenario:

  • the user enters the user id and logs in to the application
  • the user then enters the user name and age and wants to update these details for the logged-in user

We’ll store the user values in the session to understand the usage of HttpServletRequest#getSession() and HttpServletRequest#getSession(boolean).

First, let’s create a servlet where we’re using HttpServletRequest#getSession() in its doGet() method:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();
    session.setAttribute("userId", request.getParameter("userId"));
}

At this point, the servlet will retrieve the existing session or create a new one for the logged-in user, if it doesn’t exist.

Next, we’ll set the userName attribute in the session.

As we want to update the details of the user for the respective user id, we want the same session and do not want to create a new session to store the user name.

So now, we will use HttpServletRequest#getSession(boolean) with false value*:*

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.setAttribute("userName", request.getParameter("userName"));
    }
}

This will result in setting the userName attribute on the same session that the userId was previously set.

4. Conclusion

In this tutorial, we’ve explained the difference between HttpServletRequest#getSession() and HttpServletRequest#getSession(boolean) methods.

The complete example is available over on GitHub.


» 下一篇: Java的概率