Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
If you ask for a HTTP-session for the first time, an ID is assigned to the session, by which a user can be tracked, as she fills her shopping cart, for instance. You can see this in the pictures.
We use HttpServletRequest's getSession method . true means : create a session if there's none already, else get the current one.
The ID is retrieved by calling HTTPSession's getID method.
You can store key-value pairs in the session.
And retrieve them.
USER SPECIFIC DATA PERTAINING TO THE SESSION SHOULD BE STORED USING THE SESSION OBJECT, DEFINITELY NOT IN SERVLET VARIABLES.
ONE SINGLE SERVLET INSTANCE SERVICES MULTIPLE CLIENTS, but every client('s browser) gets its own session object.
As the second picture indicates, the servlet has been called 4 times from the browser. The first time the 'somename' value is only set, not retrieved.
Cookies are plain-text lines sent with the response from the server to the browser, that stores them, and sends them back to the server with the next request.
TO SUPPORT SESSIONS THE BROWSER SHOULD ACCEPT COOKIES ! The session-id is then passed back and forth in a cookie.
Everything is not lost, if the browser doesn't allow cookies, though, because the session id can also be passed as part of the URL.
The encodeURL method adds the id as jsessionid to the URL, if necessary.
What we've done is associate a simple String with the session object, but you can associate any object, your ShoppingCart, for instance, or a Vector, or some other Collection. Whatever you deem appropriate.
Creation time and last access time in milliseconds on the server.
Default session timeout value for Tomcat is 30 minutes, which can be configured differently.
It can even be changed for one session : 300 seconds.
Or the session can be terminated.