SESSION TRACKING.

Slides:



Advertisements
Similar presentations
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
Advertisements

7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
Session Tracking Problem: Identifizierung und Speicherung persönlicher Daten Warenkorb Lösung: Session mit ID Anmeldung ID REQ + ID RES ID: JKLMGHNB45kdse43k.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
Servlet Session Tracking. 2 Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information: Information.
Servlet Session Tracking II Session API All material and examples are from
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
Java Servlet Technology. Introduction Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages Servlet specification.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
Session Tracking - 2 Lec 32. Last Lecture Review  Session Tracking – why?  Need to store state – typical solutions Cookies – already learned URL Rewriting.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 9 Session Tracking. Session Tracking Basics Accessing the session object associated with the current request: Call request.getSession to get an.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
® IBM Software Group © 2007 IBM Corporation Best Practices for Session Management
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
CSCI 6962: Server-side Design and Programming Java Server Faces Scoping and Session Handling.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
JAVA Sessions 1. What is Session Tracking? There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular,
Session Tracking Lec 31. Revisiting Session Tracking HTTP is a stateless protocol  Every request is considered independent of every other request Many.
Cookies. Cookie A cookie is a piece of textual information Send by the Web server to the client browser Every time the browser visits the Web site again,
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
©SoftMooreSlide 1 Session Tracking with Servlets.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
Session Tracking Parts of this presentation was provided by SSE.
©SoftMooreSlide 1 Cookies. ©SoftMooreSlide 2 Cookies Basic idea –web application sends a simple name/value pair to the client –when the client connects.
1 Servlets – Part 2 Representation and Management of Data on the Web.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
JSP Implicit Objects CS 422 Dick Steflik.
Java Servlets By: Tejashri Udavant..
Sessions Many interactive Web sites spread user data entry out over several pages: Ex: add items to cart, enter shipping information, enter billing information.
Servlets Hits Counter 20-Jul-18.
Session Tracking in Servlets
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Sessions.
Java Servlets II: Session Tracking
Servlet Session Tracking
Servlets and Java Server Pages
Servlets CEN /28/2018 Copyright 2001 Ege Consulting, Inc.
CS320 Web and Internet Programming Cookies and Session Tracking
All You Ever Wanted To Know About Servlets
Handling State in Web Applications
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
CS3220 Web and Internet Programming Cookies and Session Tracking
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
Sessions Many interactive Web sites spread user data entry out over several pages: Ex: add items to cart, enter shipping information, enter billing information.
CNT 4714: Enterprise Computing Spring 2009
Web Search Interfaces.
Web Search Interfaces by Ray Mooney
CS3220 Web and Internet Programming Cookies and Session Tracking
Pre-assessment Questions
Servlet Session Tracking: Session API
Presentation transcript:

SESSION TRACKING

The need for Session Tracking Session Tracking: is the capability of a server to maintain the current state of a single client’s sequential requests 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? There are three typical solutions to this problem: cookies, URL rewriting and hidden form fields

Cookies You can use cookies to store an ID for a shopping session; with each subsequent connection, you can look up the current session ID and then use that ID to extract information about that session from a lookup table on the server machine. 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); Servlets have a higher-level API that handles the following tasks: – Extracting cookie that stores session identifier – Setting appropriate expiration time for cookie – Associating the hash tables with each request – Generating the unique session identifiers

URL Rewriting In this approach, the 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 – Must encode all URLs that refer to your own site – All pages must be dynamically generated – Fails for bookmarks and links from other sites Note: If you use URL rewriting for session tracking, most or all of your pages will have to be dynamically generated. You cannot have any static HTML pages that contain hyperlinks to dynamic pages at your site.

Hidden Form Fields Hidden Form Field is an invisible text field used for maintain the state of a user. HTML forms can have an entry that looks like the following <INPUT TYPE="HIDDEN" NAME="session" VALUE="..."> This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. This hidden field can be used to store information about the session • Advantage – Works even if cookies are disabled or unsupported • Disadvantages – Lots of tedious processing – All pages must be the result of form submissions It only works if every page is dynamically generated by a form submission.

Session Tracking using HttpSession Servlets provide an outstanding session-tracking solution: the HttpSession API . This high-level interface is built on top of cookies or URL rewriting. Using sessions in servlets involves four basic steps: 1. Accessing the session object associated with the current request – Call request.getSession to get HttpSession object, which is a simple hashtable for storing user-specific data HttpSession session = request.getSession(); It returns the current session associated with this request If no session ID is found in an incoming cookie or attached URL information, the system creates a new , empty session.

HttpSession session = request HttpSession session = request.getSession(false); Which returns null if no session already exists for the current client. 2. Looking up information associated with a session. – Call getAttribute on the HttpSession object, cast the return value to the appropriate type, and check whether the result is null. session.getAttribute(“key”) Which returns a previously stored value associated with the given key attribute. It returns an object type, and you must typecast to specific type of data. It returns null if there is no such attribute

3. Storing information in a session. – Use setAttribute with a key and a value to store the information session.setAttribute(“key”,value); 4. Discarding session data. - Remove only the data your servlet created. Call removeAttribute(“key”) to discard the value associated with the specific key. Delete the whole session in the current web application. You can call invalidate() to discard an entire session. - Log the user out an delete all sessions belonging to him or her. You can call logout() to log the client out of the web server and invalidate all sessions associated with that user.

Session Tracking Basics: Sample Code HttpSession session = request.getSession(); SomeClass value = (SomeClass)session.getAttribute("someID"); if (value == null) { value = new SomeClass(...); session.setAttribute("someID", value); } doSomethingWith(value);

Session-Tracking API Methods available in the HttpSession public Object getAttribute(String name) This method extracts a previously stored value from a session object. It returns null if no value is associated with the given name. public Enumeration getAttributeNames() This method returns the names of all attributes in the session. public void setAttribute(String name, Object value) This method associates a value with a name. If the object supplied to setAttribute implements the HttpSessionBindingListener interface, the object’s valueBound method is called after it is stored in the session. Similarly,if the previous value implements HttpSessionBindingListener, its valueUnbound method is called.

public void removeAttribute(String name) This method removes any values associated with the designated name. public void invalidate() This method invalidates the session and unbinds all objects associated with it public void logout() This method logs the client out of the Web server and invalidates all sessions associated with that client. public String getId() This method returns the unique identifier generated for each session.

public boolean isNew() This method returns true if the client (browser) has never seen the session, It returns false for preexisting sessions. public long getCreationTime() This method returns the time in milliseconds since midnight, January 1, 1970(GMT) at which the session was first built. public long getLastAccessedTime() This method returns the time in milliseconds since midnight, January 1, 1970(GMT) at which the session was last accessed by the client. public int getMaxInactiveInterval() public void setMaxInactiveInterval(int seconds) Gets or sets the amount of time session should go without access before being invalidated. A negative value specifies that the session should never time out.

Encoding URLs Sent to the Client If you use URL rewriting for session tacking, there are two possible situations in which you might use URLs that refer to your own site. • Code that generates hypertext links back to same site: URLs are embedded in the web page that the servlet generates. These URLs should be passed through the encodeURL method of HttpServletResponse. 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 originalurl = "order-page.html"; String encodedurl = response.encodeURL(originalurl); • Code that does sendRedirect to own site: Pass the URL that refers to your own site in a sendRedirect call (i.e, placed into the Location response header) String originalurl = "order-page.html"; String encodedurl = response.encodeRedirectURL(originalurl); response. sendRedirect(encodedurl);

A Servlet that Shows Per-Client Access Counts public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); synchronized(session) { String heading; Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = accessCount + 1; session.setAttribute("accessCount", accessCount);

PrintWriter out = response. getWriter(); … out PrintWriter out = response.getWriter(); … out.println("<HTML>\n" + "<CENTER>\n" + "<H1>" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1>\n" + "<TR ">\n" + " <TH>Info Type<TH>Value\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TABLE>\n" + "</CENTER></BODY></HTML>");

A Servlet that Shows Per-Client Access Counts: User 1(first visit)

A Servlet that Shows Per-Client Access Counts: User 1(next visit)

A Servlet that Shows Per-Client Access Counts: User 2

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(); ArrayList previousItems =(ArrayList)session.getAttribute("previousItems"); if (previousItems == null) { previousItems = new ArrayList(); session.setAttribute("previousItems", previousItems); } String newItem = request.getParameter("newItem"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Items Purchased"; out.println("<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY><H1>" + title + "</H1>");

synchronized(previousItems) { if (newItem. = null) { previousItems synchronized(previousItems) { if (newItem != null) { previousItems.add(newItem); } if (previousItems.size() == 0) { out.println("<I>No items</I>"); else { out.println("<UL>"); for(int i=0; i<previousItems.size(); i++) { out.println("<LI>" + (String)previousItems.get(i)); out.println("</UL>"); out.println("</BODY></HTML>"); } }