The document discusses session tracking in web applications. A session allows servers to track interactions with clients over time. Traditionally, sessions were tracked using hidden form fields, URL rewriting, or persistent cookies. The Java servlet API provides an easier session tracking mechanism using HttpSession objects. The API handles associating session data on the server with clients using cookies or URL parameters. Servlets access session data by calling getSession on the HttpRequest to retrieve an HttpSession object, then calling setAttribute and getAttribute to store and retrieve objects in the session. This allows servlets to maintain shopping carts and other stateful data across multiple requests.
2. WHAT IS A
SESSION ?
2
•A session can be defined as a series of related
interactions between a single client and the Web
server over a period of time.
•To track data among requests in a session is
known as session tracking.
3. Session Tracking 3
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, how can
server determine which previously created cart is
theirs?
4. SESSION TRACKING WITH
SERVLETS
•HTTP is a stateless protocol.
•We must have each user introduce themselves in some
way.
•We’ll look at traditional session tracking and then look
at the Session Tracking API.
6. SESSION TRACKING USING HIDDEN
VALUES
6
You can track session by passing data from the servlet to the client
as hidden value in a dynamically generated HTML form by
including a field like this:
<input type=”hidden” name=”lastName” value=”Smith”>
So the next request will submit the data back to the servlet. The
servlet retrieves this hidden value just like any other parameter
value using the getParameter method.
7. EXAMPLE: USING HIDDEN VALUES IN
THE REGISTRATION FORM
7
•This example creates a servlet that processes a registration
form.
•The client first submits the form using the GET method.
•The server collects the data in the form, displays the data
to the client, and asks the client for confirmation.
•The client confirms it by submitting the request with the
hidden values using the POST method.
• Finally, the servlet writes the data to a database.
8. EXAMPLE: USING HIDDEN VALUES IN
THE REGISTRATION FORM, CONT.
8
RegistrationRegistration RunRun
9. Session Tracking 9
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. Session Tracking 10
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
◦ Lots of tedious processing
◦ Must encode all URLs that refer to your own site
◦ Links from other sites and bookmarks can fail
11. USER AUTHORIZATION
• The web server requests the user name and password.
The information is available to any servlet that needs it.
• The browser resends the name and password with each
subsequent request.
• Data about the user and the user’s state can be saved in a
shared object.
12. SHARED OBJECTS
• A convenient way to store data associated with a user.
•There are likely to be many servlets running.
• They can collaborate through a shared object.
• Only one instance of the shared object should exist.
• It has to be available (in the classpath) of the servlets
that needs it.
• It will be used by several threads and therefore should
protect itself against simultaneous access.
• We’ll look at a shared object and two servlets that use it.
13. VISITTRACKER.JAVA
// Servlet collaboration can be done through a shared object.
// Any servlet has access to this object and it only has one
// instance.
// It maintains a hash table of names and dates.
// Sections of code that must not be executed simultaneously
// are called critical sections. Java provides the synchronized
// keyword to protect these critical sections. For a synchronized
// instance method, Java obtains an exclusive lock on the class
// instance.
14. import java.util.*;
public class VisitTracker {
private Map nameDatePairs;
private static VisitTracker instance = new VisitTracker();
private VisitTracker() { // private constructor
nameDatePairs = new HashMap();
}
public static VisitTracker getInstance() { return
instance; }
synchronized public void addVisit(String userName) {
nameDatePairs.put(userName, new Date());
}
16. COOKIES
• A cookie is a bit of information sent by a web server
to a browser that can later be read back from that browser.
• The server can take that bit of information and use it as a
key to recover information about prior visits. This
information may be in a database or a shared object.
• Cookies are read from the request object by calling
getCookies() on the request object.
• Cookies are placed in the browser by calling addCookie()
on the response object.
17. SESSION TRACKING USING
COOKIES
17
•You can track sessions using cookies.
•Cookies are small text files that store sets of name=value pairs on
the disk in the client’s computer.
•Cookies are sent from the server through the instructions in the
header of the HTTP response.
•The instructions tell the browser to create a cookie with a given
name and its associated value.
•If the browser already has the cookie with the key name, the value
will be updated.
•The browser will then send the cookie with any request submitted
to the same server.
•Cookies can have expiration dates set, after which the cookies will
not be sent to the server.
18. USING COOKIES
// CookieDemo.java
// This servlet uses a cookie to determine when the
// last visit by this browser occurred. It makes use of
// the VisitTracker object.
// Cookies normally expire as soon as the browser exits.
// We want the cookie to last one year and so we use
// setMaxAge(seconds) on the cookie.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
19. public class CookieDemo extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
Cookie[] c = req.getCookies();
// If this person has been here before then we should have
// a cookiedemouser field assigned to a unique id.
String id = null;
20. if (c!=null) { // we may have the cookie we are after
for (int i=0;i<c.length;i++) {
if (c[i].getName().equals("cookiedemouser")) {
id = c[i].getValue();
}
break;
}
}
21. if (id == null) {
// They have not been here before and need a
// cookie. We get a unique string and make sure
// it is of the 'query string' form.
String uid = new java.rmi.server.UID().toString();
id = java.net.URLEncoder.encode(uid);
Cookie oreo = new Cookie("cookiedemouser",id);
oreo.setMaxAge(60*60*24*365);
res.addCookie(oreo);
}
VisitTracker visit = VisitTracker.getInstance();
Date last = visit.lastVisit(id);
if(last == null) out.println("Welcome, you were never here
before");
else out.println("Your last visit was on " + last);
visit.addVisit(id);
}
}
22. Session Tracking 22
ROLLING YOUR OWN SESSION
TRACKING: COOKIES
Idea: associate cookie with data on server
String sessionID = makeUniqueString();
Hashtable sessionInfo = new Hashtable();
Hashtable 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
◦ Generating the unique session identifiers
23. SESSION TRACKING USING THE
SERVLET API
23
•The problems of session tracking with hidden data and cookies
are that data are not secured and difficult to deal with large set of
data.
•Java servlet API provides a session tracking tool, which enables
tracking of a large set of data. Data can be stored as objects. Data
are kept on the server side so they are secure.
24. THE HTTPSESSION CLASS
24
•To use the Java servlet API for session tracking, first create a
session object using the getSession method in the
HttpServletRequest interface like this:
HttpSession session = request.getSession(true);
•This obtains the session or creates a new session if the client
does not have a session on the server.
•The HttpSession class provides the methods for reading and
storing data to the session, and for manipulating the session.
25. THE SESSION TRACKING API
Session objects live on the server
Automatically associated with client via cookies or
URL-rewriting
◦ Use request.getSession(true) to get either existing or
new session
Behind the scenes, the system looks at cookie or URL extra
info and sees if it matches the key to some previously stored
session object. If so, it returns that object. If not, it creates a
new one, assigns a cookie or URL info as its key, and returns
that new session object.
Hashtable-like mechanism lets you store arbitrary
objects inside session
◦ setAttribute (putValue ) stores values
◦ getAttribute (getValue) retrieves values
25Session Tracking
26. ACCESSING SESSION DATA
HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getAttribute("shoppingCart")
;
if (cart == null) { // No cart already in session
cart = new ShoppingCart();
session.setAttribute("shoppingCart", cart);
}
doSomethingWith(cart);
26Session Tracking
27. HTTPSESSION METHODS
getAttribute (getValue)
◦ Extracts a previously stored value from a session
object. Returns null if no value is associated with given
name.
setAttribute (putValue)
◦ Associates a value with a name. Monitor changes:
values implement HttpSessionBindingListener.
removeAttribute (removeValue )
◦ Removes values associated with name.
getAttributeNames (getValueNames)
◦ Returns names of all attributes in the session.
getId
◦ Returns the unique identifier.
27Session Tracking
28. HTTPSESSION METHODS
(CONTINUED)
isNew
◦ Determines if session is new to client (not to page)
getCreationTime
◦ Returns time at which session was first created
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 the session and unbinds all
objects associated with it
28Session Tracking
29. A SERVLET SHOWING PER-CLIENT
ACCESS COUNTS
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
HttpSession session = request.getSession(true);
String heading;
Integer accessCount =
(Integer)session.getAttribute("accessCount");
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
session.setAttribute("accessCount", accessCount);
29Session Tracking
34. SUMMARY
Although it usually uses cookies behind the
scenes, the session tracking API is higher-level
and easier to use than the cookie API
◦ If server supports URL-rewriting, your code is
unchanged
Session information lives on server
◦ Cookie or extra URL info associates it with a user
Obtaining session
◦ request.getSession(true)
Associating values with keys
◦ session.setAttribute (or session.putValue)
Finding values associated with keys
◦ session.getAttribute (or session.getValue)
Always check if this value is null
34Session Tracking