0% found this document useful (0 votes)
35 views

08 Session Tracking

Uploaded by

Sherin Roman
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

08 Session Tracking

Uploaded by

Sherin Roman
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

© 2010 Marty Hall

S
Session
i Tracking
T ki
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
3 Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2010 Marty Hall

For live Java EE training, please see training courses


at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring, g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP, JSP and this tutorial.tutorial Available at public
venues,Customized
or customized versions
Java EE Training: can be held on-site at your
http://courses.coreservlets.com/
organization. Contact [email protected] for details.
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
• Implementing session tracking from scratch
• Using basic session tracking
• Understanding the session-tracking API
• Diff
Differentiating
ti ti between
b t server and
d browser
b
sessions
• Encoding URLs
• Storing immutable objects vs. storing
mutable objects
• Tracking user access counts
• Accumulating g user purchases
p
• Implementing a shopping cart
5 • Building an online store

© 2010 Marty Hall

Overview

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
6 Developed and taught by well-known author and developer. At public venues or onsite at your location.
Session Tracking
and E-Commerce
• Why session tracking?
– When clients at on-line store add item to their shopping
cart, how does server know what’s already in cart?
– When clients decide to proceed to checkout,
checkout how can
server determine which previously created cart is theirs?

Dilbert used with permission of United Syndicates Inc.


7

Rolling Your Own Session


Tracking: Cookies
• Idea: associate cookie with data on server
String sessionID = makeUniqueString();
HashMap sessionInfo = new HashMap();
HashMap globalTable = findTableStoringSessions();
globalTable.put(sessionID, sessionInfo);
Cookie sessionCookie =
new Cookie("JSESSIONID", sessionID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);

• 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

Rolling Your Own Session


Tracking: Hidden Form Fields
• Idea:
<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">

• 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

The Java Session-


Tracking
g API

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
11 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Session Tracking Basics


• Access the session object
– Call request.getSession to get HttpSession object
• This is a hashtable associated with the user
• Look up information associated with a
session.
– Call ggetAttribute on the HttpSession
p object,
j , cast the
return value to the appropriate type, and check whether
the result is null.
• Store information in a session
session.
– Use setAttribute with a key and a value.
• Discard session data.
data
– Call removeAttribute discards a specific value.
12 – Call invalidate to discard an entire session.
Session Tracking Basics:
Sample Code
HttpSession session = request.getSession();
synchronized(session) {
SomeClass value =
(SomeClass)session.getAttribute("someID");
if (value == null) {
value = new SomeClass(...);
session.setAttribute("someID", value);
}
doSomethingWith(value);
}

• 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

© 2010 Marty Hall

Storing Simple Values

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
18 Developed and taught by well-known author and developer. At public venues or onsite at your location.
A Servlet that Shows Per-Client
Access Counts
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest
p ( p q request,
q ,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
request getSession();
synchronized(sesssion) {
String heading;
Integer accessCount =
(Integer)session.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome
Welcome, Newcomer";
Newcomer ;
} else {
heading = "Welcome Back";
accessCount =
new Integer(accessCount.intValue() + 1);
}
session.setAttribute("accessCount", accessCount);
19

A Servlet that Shows Per-Client


Access Counts (Continued)
PrintWriter out = response.getWriter();

out.println
(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>"
<H1> + heading + "</H1>\n"
</H1>\n +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +

" <TD>Number of Previous Accesses\n" +
" <TD>" + accessCount
C t + "\
"\n"" +
"</TABLE>\n" +
"</CENTER></BODY></HTML>");
20
}
A Servlet that Shows Per-Client
Access Counts: User 1

21

A Servlet that Shows Per-Client


Access Counts: User 2

22
© 2010 Marty Hall

Storing Lists of Values

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
23 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Aside: Compilation Warnings re


Unchecked Types
• HttpSession does not use generics
– Since it was written pre-Java5. So, following is illegal:
HttpSession<ArrayList<String>> session =
request.getSession();
• Typecasting to a generic type results in a
compilation warning
HttpSession
Htt S i session
i = request.getSession();
t tS i ()
List<String> listOfBooks =
(List<String>)session.getAttribute("book-list");

– Still compiles and runs, but warning is annoying
• You can suppress warnings
– Put the following before line of code that does typecast:
@SuppressWarnings("unchecked")
24
Accumulating a List
of User Data
public class ShowItems extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
synchronized(session) {
@SuppressWarnings("unchecked")
List<String> previousItems =
(List<String>)session getAttribute("previousItems");
(List<String>)session.getAttribute( previousItems );
if (previousItems == null) {
previousItems = new ArrayList<String>();
session.setAttribute("previousItems", previousItems);
}
String newItem = request.getParameter("newItem");
if ((newItem != null) &&
(!
(!newItem.trim().equals("")))
It t i () l (""))) {
previousItems.add(newItem);
}
25

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

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
29 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Distributed and Persistent


Sessions
• Some servers support distributed Web apps
– L
Loadd balancing
b l i usedd tot sendd different
diff t requests
t to
t different
diff t
machines. Sessions should still work even if different hosts are hit.
• On some servers, you must call setAttribute to trigger replication
– This is a tradeoff: session duplication can be expensive,
expensive but gives
you better load balancing
• Some servers suport persistent sessions
– Session data written to disk and reloaded when server is restarted
(as long as browser stays open). Very important for web4!
• Tomcat 5 and 6 support this
• To support both,
both session data should implement
the java.io.Serializable interface
– There are no methods in this interface; it is just a flag:
public class MySessionData implements Serializable
...
}
30 – Builtin classes like String and ArrayList are already Serializable
Letting Sessions Live Across
Browser Restarts
• Issue
– By default, Java sessions are based on cookies that live in
the browser’s memory, but go away when the browser is
closed. This is often, but not always, what you want.
• Solution
– Explicitly
p y send out the JSESSIONID cookie.
• Do this at the beginning of the user’s actions
• Call setMaxAge first
• Problem
– Using a cookie with a large maxAge makes no sense
unless the session timeout ((inactiveInterval)) is also large
g
– An overly large session timeout can waste server memory
31

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

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
35 Developed and taught by well-known author and developer. At public venues or onsite at your location.

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?

Customized Java EE Training: http://courses.coreservlets.com/


Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & REST Web Services, Java 6.
37 Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like