Is Session created Automatically after the first request?

Viewed 1216

I'm newbie in web dev and I have some confusion about Sessions.

I know that :

A session is the total period of time devoted to an activity. In computer systems, a user session begins when a user logs in to or accesses a particular computer, network, or software service. It ends when the user logs out of the service, or shuts down the computer.

From this definition, I conclude that as soon as the user enters, a session is created Automatically.

BUT in many web programming language API, there are some method for creating a session after the first request!. such as Java:

request.getSession(true);

Oracle Docs:

Returns the current session associated with this request, or if the request does not have a session, creates one.

How is it possible that the client has been connected to the server and has sent a request for server but there is no session?

2 Answers

BUT in many web programming language API, there are some method for creating a session after the first request!. such as Java:

This is because http is stateless unlike other protocols SSH/ftp. In order to identify the user, Server has to create a session for user.

How is it possible that the client has been connected to the server and has sent a request for server but there is no session?

In context of HTTP: Session is not required for connection. Connection only requires server's address (and probably digital certificate for https). Session is only meant for identification of users. For blogs or news-board where identification of user is not required, Server may choose not to create session for the user.

I conclude that as soon as the user enters, a session is created Automatically.

Actually no, a session is not created unless you tell the servlet container explicitly by calling request.getSession();

Following are examples to demonstrate this :

  1. without calling request.getSession() :
  • A request made for the first time to /ServletSession; Notice that the session equals null : enter image description here

  • No JSESSIONID cookie is set in the Response Headers; Which means no session was created : enter image description here

  1. When calling request.getSession() :
  • A request made for the first time to /ServletSession; Notice that the session was created : enter image description here

  • A JSESSIONID cookie is set in the Response Headers : enter image description here

Related