O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The best part: the Container does virtually all the cookie work!

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:

image with no caption

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:

image with no caption

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required