Now that you've mastered the basics, it's time to bring out thebig iron. This week, The JSP Files explores the various techniquesavailable to "maintain state" on a JSP-based Web site. Learn about theCookie and Session objects, find out how to build a cookie-based hitcounter, and read about a simple yet effective way of protecting sensitiveWeb pages with the Session object.
The cookie-based approach is quite common; many Web sites use it, becauseit is flexible, simple, and independent of the server-side language (oncethe cookie has been saved to the client's hard drive, you can read it usingJavaScript, or PHP, or JSP, or ...) The only problem: it is dependent onthe cookie being accepted by the client.
And so, another common approach is the use of a "session" to store specificbits of information when a client visits a Web site; this session data ispreserved for the duration of the visit, and is usually destroyed on itsconclusion. A session can thus be considered a basket of information whichcontains a host of variable-value pairs; these variable-value pairs existfor the duration of the visit, and can be accessed at any point during it.This approach provides an elegant solution to the "stateless" nature of theprotocol, and is used on many of today's largest sites to track andmaintain information for personal and commercial transactions.
Every session created is associated with a unique identification string, or"session ID"; this string is sent to the client, while a temporary entrywith the same unique identification number is created on the server, eitherin a flat file or in a database. It now becomes possible to register anynumber of "session variables" - these are ordinary variables, which can beused to store textual or numeric information, and can be read from, orwritten to, throughout the session.
The session ID is transmitted to the client either via a cookie, or via theURL GET method. The client, in turn, must reference each request with thissession ID, so that the server knows which session each client isassociated with and uses the appropriate session variables for each client.In case the client doesn't support cookies and the URL method is rejectedor not used, session management capabilities and session variables will notbe available to the client, and every request will be treated as though itwere coming for the first time.
Sessions are typically left active for as long as the user's browser isopen, or for a pre-defined period. Once the user's browser is closed, orthe specified time period is exceeded, the session and all variables withinit are automatically destroyed.