Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Session Tracking Parts of this presentation was provided by www.coreservlets.com SSE."— Presentation transcript:

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

2 What is Session Tracking? l Capability of a server to maintain the current state of a single client’s sequential requests l HTTP is a “stateless” protocol, i.e., every transaction is autonomous l Need to keep track of “which client has performed what actions while at your site l Could use HTTP authentication – big hassle in high volume sites l Different ways to determine the actions that a particular client has taken

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

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

5 Rolling Your Own Session Tracking: Hidden Form Fields l Idea: Hidden Form Fields can be used to store information about the session l Advantage Easy to implement and supported by most browsers Works even if cookies are disabled or unsupported l 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

6 Example using Hidden Fields l Servlet that sends hidden fields to the browser Example: SendHiddenFields.java l User adds more data and submits the page – calls another servlet Example: MyHiddenFieldServlet.java l Combine data from the hidden fields and the new data l Go through a sequence of pages

7 Working with Cookies l Use persistent cookies to store client information l Cookie – created by server and stored by the browser during a visit l Subsequent visits can use the cookie to look up information related to that visit l Basically, associate a cookie to its corresponding visit data stored at the server side

8 Rolling Your Own Session Tracking: Cookies l 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); l 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

9 Cookie Processing Example l Write a cookie l Get the cookie content l Based on the data contained in the cookie do additional processing l Example: CookieServlet.java

10 URL-Rewriting l If the browser does not support cookies or if cookies are disabled, then, URL-Rewriting provides an alternative for session tracking l In this approach, the requested URL is modified to include a session ID l The session ID value is used by the server to look up related data for that session

11 Rolling Your Own Session Tracking: URL-Rewriting l 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 l Advantage Works even if cookies are disabled or unsupported l Disadvantages Lots of tedious processing Must encode all URLs that refer to your own site Links from other sites and bookmarks can fail

12 Session Tracking with the Servlet API l Servlet API has its own built-in support for session tracking l The HttpSession object provides this functionality l 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

13 The Session Tracking API l Session objects live on the server l 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. l Hashtable-like mechanism lets you store arbitrary objects inside session setAttribute (putValue in 2.1) stores values getAttribute (getValue in 2.1) retrieves values

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

15 HttpSession Methods l getAttribute, getValue [2.1] Extracts a previously stored value from a session object. Returns null if no value is associated with given name. l setAttribute, putValue [2.1] Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener. l removeAttribute, removeValue [2.1] Removes values associated with name. l getAttributeNames, getValueNames [2.1] Returns names of all attributes in the session. l getId Returns the unique identifier.

16 HttpSession Methods (Contd) l isNew Determines if session is new to client (not to page) l getCreationTime Returns time at which session was first created l 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 l invalidate Invalidates the session and unbinds all objects associated with it

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

18 First Visit to ShowSession Servlet

19 Eleventh Visit to ShowSession Servlet

20 Session Tracking and Shopping Carts

21 Session Tracking and Shopping Carts (Continued)

22 Summary l 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 l Session information lives on server Cookie or extra URL info associates it with a user l Obtaining session request.getSession(true) l Associating values with keys session.setAttribute (or session.putValue) l Finding values associated with keys session.getAttribute (or session.getValue) Always check if this value is null


Download ppt "Session Tracking Parts of this presentation was provided by www.coreservlets.com SSE."

Similar presentations


Ads by Google