08 Session Tracking
08 Session Tracking
S
Session
i Tracking
T ki
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Overview
• Still to be done:
– Extracting cookie that stores session identifier
– Setting appropriate expiration time for cookie
– Associating the hash tables with each request
8 – Generating the unique session identifiers
Rolling Your Own Session
Tracking: URL-Rewriting
• Idea
– Client appends some extra data on the end of each URL
that identifies the session
– Server associates that identifier with data it has stored
about that session
– E.g., http://host/path/file.html;jsessionid=1234
• Advantage
– Works even if cookies are disabled or unsupported
• Disadvantages
Di d t
– Must encode all URLs that refer to your own site
– All pages must be dynamically generated
– Fails for bookmarks and links from other sites
9
• Advantage
– Works even if cookies are disabled or unsupported
• Disadvantages
– Lots of tedious processing
– All pages must be the result of form submissions
10
© 2010 Marty Hall
• Do not need to call setAttribute again (after modifying value) if the modified
value is the same object
object. But
But, if value is immutable
immutable, modified value will be a
new object reference, and you must call setAttribute again. However, call
setAttribute every time if you want to support distributed sessions (where a
single app is distributed across multiple nodes in a cluster).
13
To Synchronize or Not to
Synchronize?
• The J2EE blueprints say not to bother
– There are no race conditions when multiple different
users access the page simultaneously
– On the face of it,
it it seems practically impossible for the
same user to access the session concurrently
• The rise of Ajax
j makes synchronization
y
important
– With Ajax calls, it is actually quite likely that two
requests from the same user could arrive concurrently
• Performance tip
– Don
Don’tt do “synchronized(this)”!
synchronized(this) !
• Use the session or perhaps the value from the session as
the label of the synchronized block
14
What Changes if Server Uses
URL Rewriting?
• Session tracking code:
– No change
• Code that generates hypertext links back to
same site:
– Pass URL through response.encodeURL.
• If server is using cookies, this returns URL unchanged
• If server is using URL rewriting, this appends the session
info to the URL
• E.g.:
String url = "order-page.html";
url = response.encodeURL(url);
• Code that does sendRedirect to own site:
– Pass URL through response.encodeRedirectURL
15
HttpSession Methods
• getAttribute
– Extracts a previously stored value from a session object.
Returns null if no value is associated with given name.
• setAttribute
– Associates a value with a name. Monitor changes: values
implement
p HttpSessionBindingListener.
p g
• removeAttribute
– Removes values associated with name.
• getAttributeNames
– Returns names of all attributes in the session.
• getId
tId
– Returns the unique identifier.
16
HttpSession Methods
(Continued)
• isNew
– Determines if session is new to client (not to page)
• getCreationTime
– Returns
R time
i at which
hi h session
i was first
fi createdd
• getLastAccessedTime
– Returns time at which session was last sent from client
• getMaxInactiveInterval, setMaxInactiveInterval
– Gets or sets the amount of time session should go without
access before being invalidated
• invalidate
– Invalidates current session
17
21
22
© 2010 Marty Hall
Accumulating a List
of User Data (Continued)
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Items Purchased";
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
o t println(docT pe +
out.println(docType
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
<H1> + title + "</H1>");
"<H1>" </H1> );
if (previousItems.size() == 0) {
out.println("<I>No items</I>");
} else {
out.println( <UL> );
out.println("<UL>");
for(String item: previousItems) {
out.println(" <LI>" + item);
}
p
out.println("</UL>");
}
out.println("</BODY></HTML>");
}
26 }}
Accumulating a List
of User Data: Front End
27
Accumulating a List
of User Data: Result
28
© 2010 Marty Hall
Advanced Features
An On-Line Bookstore
• Session tracking code stays the same as in
simple
i l examples
l
• Shopping cart class is relatively complex
– Id
Identifies
ifi items
i by
b a unique
i catalog
l ID
– Does not repeat items in the cart
• Instead, each entry has a count associated with it
• If count reaches zero, item is deleted from cart
• Pages built automatically from objects that
h
have descriptions
d i ti off books
b k
32
An On-Line Bookstore
33
An On-Line Bookstore
34
© 2010 Marty Hall
Wrap-up
Summary
• Sessions do not travel across network
– Only unique identifier does
• Get the session
– request.getSession
S i
• Extract data from session
– session.getAttribute
session getAttribute
• Do typecast and check for null
• If you cast to a generic type, use @SuppressWarnings
• Put data in session
– session.setAttribute
• Custom
C t classes
l iin sessions
i
– Should implement Serializable
36
© 2010 Marty Hall
Questions?