Servlet Session Tracking. 2 Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information: Information.

Slides:



Advertisements
Similar presentations
7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
Advertisements

Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
Servlets and a little bit of Web Services Russell Beale.
CSE 154 LECTURE 13: SESSIONS. Expiration / persistent cookies setcookie("name", "value", expiration); PHP $expireTime = time() + 60*60*24*7; # 1 week.
Servlet Session Tracking II Session API All material and examples are from
Chapter 10 Maintaining State Information Using Cookies.
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.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
 A cookie is a piece of text that a Web server can store on a user's hard disk.  Cookie data is simply name-value pairs stored on your hard disk by.
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Comp2513 Java Servlets and Sessions Daniel L. Silver, Ph.D.
IT533 Lectures Session Management in ASP.NET. Session Tracking 2 Personalization Personalization makes it possible for e-businesses to communicate effectively.
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Web Programming Language Week 7 Dr. Ken Cosh Security, Sessions & Cookies.
Chapter 8 Cookies And Security JavaScript, Third Edition.
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.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Session Tracking - 2 Lec 32. Last Lecture Review  Session Tracking – why?  Need to store state – typical solutions Cookies – already learned URL Rewriting.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
Mark Dixon 1 03 – Passing Data between pages: Forms, Sessions, & Query Strings.
Chapter 6 Server-side Programming: Java Servlets
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
DAT602 Database Application Development Lecture 16 Java Server Pages Part 2.
STATE MANAGEMENT.  Web Applications are based on stateless HTTP protocol which does not retain any information about user requests  The concept of state.
® 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.
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,
CP476 Internet Computing CGI1 Cookie –Cookie is a mechanism for a web server recall info of accessing of a client browser –A cookie is an object sent by.
Session Tracking Lec 31. Revisiting Session Tracking HTTP is a stateless protocol  Every request is considered independent of every other request Many.
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:
SE-2840 Dr. Mark L. Hornick1 Servlet Threads and Sessions.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
©SoftMooreSlide 1 Session Tracking with Servlets.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
MIT AITI 2004 JSP – Lecture 4 Sessions and Cookies.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
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.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
COOKIES AND SESSIONS.
HTTP Transactions 1. 2 Client-Server Model 3 HTTP HyperText Transport Protocol Native protocol for WWW Sits on top of internet’s TCP/IP protocol HTTP.
Net-centric Computing Servlets & JSP. Lecture Outline  Tracking Sessions  Cookies  Examples  JSP  Differences between JSP and Servlets  JSP Constructs.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
Sessions Many interactive Web sites spread user data entry out over several pages: Ex: add items to cart, enter shipping information, enter billing information.
ITM 352 Cookies.
Web Programming Language
Sessions.
What is Cookie? Cookie is small information stored in text file on user’s hard drive by web server. This information is later used by web browser to retrieve.
Servlet Session Tracking
Client / Session Identification Cookies
CS320 Web and Internet Programming Cookies and Session Tracking
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.
Building ASP.NET Applications
CS3220 Web and Internet Programming Cookies and Session Tracking
Web Programming Language
Pre-assessment Questions
Servlet Session Tracking: Session API
Presentation transcript:

Servlet Session Tracking

2 Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information: Information about the session A session starts when the user logs in or otherwise identifies himself/herself, and continues until the user logs out or completes the transaction (for example, makes a purchase) Information about the user User information must generally be maintained much longer than session information (for example, remembering a purchase) This information must be stored on the server, for example on a file or in a database

3 Server capabilities Servlets, like Applets, can be trusted or untrusted A servlet can use a unique ID to store and retrieve information about a given session User information usually requires a login ID and a password Since servlets don’t quit between requests, any servlet can maintain information in its internal data structures, as long as the server keeps running A trusted servlet can read and write files on the server, hence can maintain information about sessions and users even when the server is stopped and restarted An untrusted servlet will lose all information when the servlet or server stops for any reason This is sometimes good enough for session information This is almost never good enough for user information

4 Session tracking HTTP is stateless: When it gets a page request, it has no memory of any previous requests from the same client This makes it difficult to hold a “conversation” Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests The server must be able to keep track of multiple conversations with multiple users Session tracking is keeping track of what has gone before in this particular conversation Since HTTP is stateless, it does not do this for you You have to do it yourself, in your servlets You can do this by maintaining a session ID for each user

5 Session tracking solutions Hidden fields can be used to store a unique ID for the session Cookies are small files that the servlet can store on the client computer, and retrieve later URL rewriting: You can append a unique ID after the URL to identify the user Java’s Session Tracking API can be used to do most of the work for you

6 Hidden fields Advantages: All you need to know is how to read servlet parameters String sessionID = getParameter("sessionID"); out.println(" "); Efficient: Minimizes repeated calls to the server Disadvantages: Not kept across sessions, so useless for maintaining persistent information about a user Since the session ID must be incorporated into every HTML page, every HTML page must be dynamically generated Hidden fields are good for session tracking (holding a “conversation” with the user)--they’re simple and efficient

7 Using hidden fields, I The very first request that the user sends you will (typically) have null for the value of your hidden field When your servlet sees the null, it can assign a unique session ID and include it in a hidden field in the response Each subsequent request will include this hidden field The servlet can keep session information in some data structure of its own, keyed by the session ID This is feasible because the servlet does not quit between requests, so it can maintain information in its memory You cannot assume the user will end the session the way you think she should (say, by logging off) If the session data is sufficiently “old,” you need to assume the user isn’t coming back, and discard the session data

8 Using hidden fields, II The session ID does not have to be the only hidden field You can have other fields in addition to, or instead of, a session ID field This might be a good way to keep track of small amounts of simple information during a session Hidden fields are not particularly well suited to holding complex or structured information In all cases, hidden fields are good only for storing session information Information in servlet data structures will eventually be lost (when the servlet quits) or get old and be discarded

9 Cookies A cookie is a small bit of text sent to the client that can be read again later Limitations (for the protection of the client): Not more than 4KB per cookie (more than enough in general) Not more than 20 cookies per site Not more than 300 cookies total Cookies are not a security threat Cookies can be a privacy threat Cookies can be used to customize advertisements Outlook Express allows cookies to be embedded in A servlet can read your cookies Incompetent companies might keep your credit card info in a cookie Netscape and Firefox let you refuse cookies to sites other than that to which you connected

10 Using cookies import javax.servlet.http.*; Constructor: Cookie(String name, String value) Assuming request is an HttpServletRequest and response is an HttpServletResponse, response.addCookie(cookie); Cookie[ ] cookies = request.getCookies(); String name = cookies[i].getName(); String value = cookies[i].getValue(); There are, of course, many more methods in the HttpServletRequest, HttpServletResponse, and Cookie classes in the javax.servlet.http package

11 Some more Cookie methods public void setComment(String purpose ) public String getComment() public void setMaxAge(int expiry ) public int getMaxAge() Max age in seconds after which cookie will expire If expiry is negative, delete when browser exits If expiry is zero, delete cookie immediately setSecure(boolean flag ) public boolean getSecure() Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

12 What cookies are good for Advantages: Java’s Session Tracking API (to be discussed) makes cookies dead simple to use Cookies can easily contain more data than hidden fields Data is stored on the client computer, not on yours This saves space on the server May let you avoid keeping track of multiple(session) data structures Disadvantages: Data is stored on the client computer, not on yours This means the data is neither safe nor secure Should not be used for user data--cookies may be discarded or the user may contact the server from another computer Users can tell their browser to turn cookies off Cookies are good for keeping session data, not user data

13 Java’s session tracking API, I Here’s how you get a session ID from the request: HttpSession session = request.getSession(); Here’s what this does for you: If the session includes a session ID cookie then find the session matching that session ID else (no session ID cookie or no matching session) create a new session This method does all the cookie work for you Whether the session is a new one or a pre-existing one, you get an HttpSession for it

14 Java’s session tracking API, II Here’s how you send a cookie in the response: HttpSession session = request.getSession(); What this does for you: Creates a new HttpSession object, or retrieves a previous one Creates a unique session ID Makes a new cookie object Associates the cookie with the session ID Puts the cookie in the response (under the Set-Cookie header) Notice that: This is exactly the same call as in the previous slide The message is sent to the request, not the response

15 Using an HttpSession session.setAttribute(String name, Object value) You can save objects in an HttpSession object = session.getAttribute(String name) You can retrieve your saved objects by name Enumeration e = session.getAttributeNames() You can find the names of all your objects session.removeAttribute(String name) You can get rid of an object you no longer need boolean session.isNew() true if the session is newly created, rather than retrieved String id = session.getId() You can get the session ID (if you’re debugging, or just curious)

16 Quitting an HttpSession session.invalidate() Quits the session and unbinds any objects in it milliseconds = session.getCreationTime() (since midnight January 1, 1970 GMT) milliseconds = session.getLastAccessedTime() (again, since 1970) session.setMaxInactiveInterval(int seconds) Sets the time until the session is automatically invalidated int seconds = session.getMaxInactiveInterval() So the Session API does nearly everything you need!

17 URL rewriting If the user has cookies turned off, you can use URL rewriting URL rewriting is only used as a backup for cookies URL rewriting adds the session ID to the end of every URL: URL + ;jsessionid=0ABCDEF98765 This is almost automatic, but: Cookies must fail, and You must explicitly “encode” (add the extra information to) your URLs, for example: out.println(" click me ");

18 What the Container does If you are using the Session API, When the Container (Tomcat) starts a new session, it sends a cookie and does URL rewriting If it gets a cookie back, it abandons URL rewriting The Container can’t just send a cookie and see if it gets it back, because it can’t tell that what it gets back is from the same session A “dumb” Container may always send the cookie and do URL rewriting each time

19 More HttpServletRequest methods public HttpSession getSession() Gets the session object for this request (or creates one if necessary) public Enumeration getHeaderNames() Gets an Enumeration of all the field names in the HTTP header public String getHeader(String name ) Given the header name, return its value public int getIntHeader(String name ) Given the header name, return its value as an int Returns -1 if no such header Could throw a NumberFormatException public Enumeration getHeaders(String name ) Given the header name, return an Enumeration of all its values

20 Summary: Session Tracking API The session tracking API is in javax.servlet.http.HttpSession and is built on top of cookies To use the session tracking API : Create a session: HttpSession session = request.getSession(); Returns the session associated with this request If there was no associated session, one is created Store information in the session and retrieve it as needed: session.setAttribute( name, value ); Object obj = getAttribute( name ); Session information is automatically maintained across requests To allow URL rewriting, use response.encodeURL( yourURL )

21 Other uses of cookies Cookies were devised for managing sessions, but you can use them for other things You can use cookies for storing small amounts of information on your client computers By default, cookies are discarded when the browser quits cookie.setMaxAge(int seconds ) If seconds is positive, cookie should persist for that long If seconds is negative, cookie is deleted when browser quits If seconds is zero, cookie is deleted immediately

22 Summary A session is a continuous interaction with the user HTTP is stateless, so the programmer must do something to remember session information There are multiple ways to remember session information The session ends when the user quits the browser (or a session may be set to time out) Some information must be kept longer than just within a session For example, if the user orders a product, that information must be kept in a database Long-term storage of information requires that the servlet have some additional privileges

23 The End