In this quick tutorial, we’ll see the difference between calling HttpServletRequest#getSession() and HttpServletRequest#getSession(boolean).
_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.
In this example, we are considering this scenario:
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