Skip to content
Advertisement

Session created by Tomcat

I am learning session with servlets and i read in the book that to create a session we need to call as below.

HttpSession session = request.getSession()

This causes the web container to create a session ID and send it back to client so that client can attach it with every subsequent request to the server. When i open developer tools in chrome under request headers in network tab i do see a cookie header.

Cookie: JSESSIONID=F92

Below is what i did in my login servlet

JavaScript

Index.jsp

JavaScript

My question is that even if i remove the getSession() call i still see the cookie in the network tab. Is there a default session associated with every request by tomcat?

Advertisement

Answer

On Tomcat sessions are established lazily, when they are needed. There are basically a couple of situations where sessions are created:

  • if you call request.getSession() or request.getSession(true) a session is always established,
  • if you authenticate users against Tomcat’s user database a session might be created depending on the authentication method. Most notably if you use form authentication (see this tutorial) a session is always established,
  • JSP pages create sessions unless you add the <%page session="false"%> directive (see Why set a JSP page session = “false” directive?).

Browsers remember cookies, so the presence of a JSESSIONID is not an indication of the presence of a session (it might be there from a previous test). To test for a presence of a session use request.getSession(false). For example:

JavaScript

Edit: I added the case of a JSP page creating sessions.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement