22
Session Tracking Parts of this presentation was provided by www.coreservlets.com SSE

Session Tracking Parts of this presentation was provided by SSE

Embed Size (px)

DESCRIPTION

Session Tracking and E-Commerce l Advantages of 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?

Citation preview

Page 1: Session Tracking Parts of this presentation was provided by  SSE

Session Tracking

Parts of this presentation was provided by www.coreservlets.com

SSE

Page 2: Session Tracking Parts of this presentation was provided by  SSE

What is Session Tracking?

Capability of a server to maintain the current state of a single client’s sequential requests

HTTP is a “stateless” protocol, i.e., every transaction is autonomous

Need to keep track of “which client has performed what actions while at your site

Could use HTTP authentication – big hassle in high volume sites

Different ways to determine the actions that a particular client has taken

Page 3: Session Tracking Parts of this presentation was provided by  SSE

Session Tracking and E-Commerce

Advantages of 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?

Page 4: Session Tracking Parts of this presentation was provided by  SSE

Different ways of Session Tracking Hidden Form Fields Cookies URL Rewriting Built-in Session Tracking functionality of Servlet

API

Page 5: Session Tracking Parts of this presentation was provided by  SSE

Rolling Your Own Session Tracking: Hidden Form Fields

Idea:• Hidden Form Fields can be used to store information about the session <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">

Advantage• Easy to implement and supported by most browsers• Works even if cookies are disabled or unsupported

Disadvantages• Hidden fields must be created in a particular sequence• Can’t use the back button without loosing information• Lots of tedious processing• All pages must be the result of form submissions

Page 6: Session Tracking Parts of this presentation was provided by  SSE

Example using Hidden Fields

Servlet that sends hidden fields to the browser• Example: SendHiddenFields.java

User adds more data and submits the page – calls another servlet• Example: MyHiddenFieldServlet.java

Combine data from the hidden fields and the new data

Go through a sequence of pages

Page 7: Session Tracking Parts of this presentation was provided by  SSE

Working with Cookies

Use persistent cookies to store client information Cookie – created by server and stored by the

browser during a visit Subsequent visits can use the cookie to look up

information related to that visit Basically, associate a cookie to its corresponding

visit data stored at the server side

Page 8: Session Tracking Parts of this presentation was provided by  SSE

Rolling Your Own Session Tracking: Cookies

Idea: associate cookie with data on serverString 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

Page 9: Session Tracking Parts of this presentation was provided by  SSE

Cookie Processing Example

Write a cookie Get the cookie content Based on the data contained in the cookie do

additional processing Example:

• CookieServlet.java

Page 10: Session Tracking Parts of this presentation was provided by  SSE

URL-Rewriting

If the browser does not support cookies or if cookies are disabled, then, URL-Rewriting provides an alternative for session tracking

In this approach, the requested URL is modified to include a session ID

The session ID value is used by the server to look up related data for that session

Page 11: Session Tracking Parts of this presentation was provided by  SSE

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

• Lots of tedious processing• Must encode all URLs that refer to your own site• Links from other sites and bookmarks can fail

Page 12: Session Tracking Parts of this presentation was provided by  SSE

Session Tracking with the Servlet API

Servlet API has its own built-in support for session tracking The HttpSession object provides this functionality Several methods within HttpSession

• setAttribute()• Binds a name/value pair to store in the current session

• getAttribute()• Used to get an object that is stored in that session

• getAttributeNames()• Returns an array of the current bound names stored in the session object

• removeAttribute()• Removes a binding from the current session

Page 13: Session Tracking Parts of this presentation was provided by  SSE

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 in 2.1) stores values• getAttribute (getValue in 2.1) retrieves values

Page 14: Session Tracking Parts of this presentation was provided by  SSE

Accessing Session DataHttpSession 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);

Page 15: Session Tracking Parts of this presentation was provided by  SSE

HttpSession Methods getAttribute, getValue [2.1]

• Extracts a previously stored value from a session object. Returns null if no value is associated with given name.

setAttribute, putValue [2.1]• Associates a value with a name. Monitor changes: values implement

HttpSessionBindingListener. removeAttribute, removeValue [2.1]

• Removes values associated with name. getAttributeNames, getValueNames [2.1]

• Returns names of all attributes in the session. getId

• Returns the unique identifier.

Page 16: Session Tracking Parts of this presentation was provided by  SSE

HttpSession Methods (Contd) 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

Page 17: Session Tracking Parts of this presentation was provided by  SSE

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);

Page 18: Session Tracking Parts of this presentation was provided by  SSE

First Visit to ShowSession Servlet

Page 19: Session Tracking Parts of this presentation was provided by  SSE

Eleventh Visit to ShowSession Servlet

Page 20: Session Tracking Parts of this presentation was provided by  SSE

Session Tracking and Shopping Carts

Page 21: Session Tracking Parts of this presentation was provided by  SSE

Session Tracking and Shopping Carts (Continued)

Page 22: Session Tracking Parts of this presentation was provided by  SSE

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 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