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.

#java #servlet

Difference Between request.getSession() and request.getSession(true)
1.10 GEEK