You do have to tell the Container that you want to create or use a session, but the Container takes care of generating the session ID, creating a new Cookie object, stuffing the session ID into the cookie, and setting the cookie as part of the response. And on subsequent requests, the Container gets the session ID from a cookie in the request, matches the session ID with an existing session, and associates that session with the current request.
Sending a session cookie in the RESPONSE:
That’s it. Somewhere in your service method you ask for a session, and everything else happens automatically.
You don’t make the new HttpSession object yourself.
You don’t generate the unique session ID.
You don’t make the new Cookie object.
You don’t associate the session ID with the cookie.
You don’t set the Cookie into the response (under the Set-Cookie header).
All the cookie work happens behind the scenes.
Getting the session ID from the REQUEST:
Look familiar? Yes, it’s exactly the same method used to generate the session ID and cookie for the response!
IF (the request includes a session ID cookie)
find the session matching that ID
ELSE IF (there’s no session ID cookie OR there’s no current session matching the session ID)
create a new session. ...