Java Reference
In-Depth Information
By default, all JavaServer Pages have access to an implicit session object.
Servlets that are not from a JSP must obtain a session object by calling the
getSession() method of the request object. Figure 12-22 displays lines 89 through
103 of the WebStocks servlet code. Using the getSession() method with an argu-
ment of true, as is done in line 89, returns the current session object; if none
exists, it creates a new session object.
FIGURE 12-22
Data is associated with a session by setting a session attribute, which can be
retrieved by subsequent requests and also removed when no longer needed. A
session attribute consists of a name associated with an object bound to the ses-
sion. Session attributes are stored on the server and only the session identifier, or
session ID, must be passed back to the browser. The browser returns the session
ID with each subsequent request, allowing identification of the user session, as
well as access to the session attributes. The session object provides the
setAttribute() method to associate a name and an object with the session.
The method will bind an object to the session, meaning it attaches the object
to the session ID. The getAttribute() method returns the object associated
with an attribute name, if it is bound to the session. The object must be down-
cast to the appropriate type. If the object does not exist, null is returned. The
removeAttribute() method removes a bound attribute name and object from
the session, if needed.
Session identifiers can be sent to the browser using URL encoding , also
called URL rewriting ; however, this requires writing significant code to add the
session ID to the URL for every transaction. By default, the servlet API uses a
cookie to store the session ID, and the browser passes the cookie to the server
with each request. A cookie is a message given to a Web browser by a Web server,
which the browser stores in a text file on the client machine and then returns to
the server with subsequent requests. No additional coding is needed for session
tracking using cookies, although custom cookies may be created for other pur-
poses. The only drawback is that the browser must be set to accept cookies or
this type of session tracking will not work. URL encoding works regardless of the
browser cookie setting; however, it requires more coding effort and also displays
the session ID in the URL.
 
Search WWH ::




Custom Search