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,

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
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.
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.
Authentication and Security Joshua Scotton.  Sessions  Login and Authentication.
Servlets and a little bit of Web Services Russell Beale.
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
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.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
IT533 Lectures Session Management in ASP.NET. Session Tracking 2 Personalization Personalization makes it possible for e-businesses to communicate effectively.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
JavaScript, Fourth Edition
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
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.
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.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CS453: State in Web Applications (Part 1) State in General Sessions (esp. in PHP) Prof. Tom Horton.
Chapter 5 HTTP Request Headers. Content 1.Request headers 2.Reading Request Headers 3.Making a Table of All Request Headers 4.Sending Compressed Web Pages.
COMP3121 E-Commerce Technologies Richard Henson University of Worcester November 2011.
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.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
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.
1 Maryland ColdFusion User Group Session Management December 2001 Michael Schuler
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).
Chapter 6 Server-side Programming: Java Servlets
Christopher M. Pascucci Basic Structural Concepts of.NET Managing State & Scope.
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.
STATE MANAGEMENT.  Web Applications are based on stateless HTTP protocol which does not retain any information about user requests  The concept of state.
PHP. $_GET / $_POST / $_SESSION PHP uses predefined variables to provide access to important information about the server and requests from a browser.
® IBM Software Group © 2007 IBM Corporation Best Practices for Session Management
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
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.
MEMBERSHIP AND IDENTITY Active server pages (ASP.NET) 1 Chapter-4.
Saving State on the WWW. The Issue  Connections on the WWW are stateless  Every time a link is followed is like the first time to the server — it has.
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.
 Shopping Basket  Stages to maintain shopping basket in framework  Viewing Shopping Basket.
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.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
Sessions Many interactive Web sites spread user data entry out over several pages: Ex: add items to cart, enter shipping information, enter billing information.
Session Tracking in Servlets
ITM 352 Cookies.
Sessions.
SESSION TRACKING.
Servlet Session Tracking
Servlets and Java Server Pages
Handling State in Web Applications
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.
Web Search Interfaces.
Pre-assessment Questions
Servlet Session Tracking: Session API
Presentation transcript:

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, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?

JAVA Sessions There are three typical solutions to this problem. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to- use interface to cookies, there are still a number of relatively tedious details that need to be handled:high-level and easy-to- use interface to cookies Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all), Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies).

JAVA Sessions 2.URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.

JAVA Sessions 3) Hidden form fields. HTML forms have an entry that looks like the following:. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

JAVA Sessions Servlets provide a solution: the HttpSession API. This is a high-level interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies if the browser supports them, but automatically revert to URL-rewriting when cookies are unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of the details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is automatically given a convenient place to store data that is associated with each session.

JAVA Sessions What is a Session ? A session is pretty much what it sounds, when a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site, the server identifies that user. So a session is a small and temporary unique connection between a server and the user enabling it to identify that user across multiple page requests or visits to that site.

JAVA Sessions What is Session Management ? Ok now you know what is a session. Session management is to use the API provided by your application server to identify the user across multiple page requests. Note that every server has it's own set of API for session management, since we are talking about 'Managing Sessions with Java Servlets', we will be making use of the Servlet API 2.2 which almost all of the Java application servers support.

JAVA Sessions Why use Session Management ? Hundreds and thousands of simultaneous users can be visiting your site and if you can identify each of them separately then it can provide tremendous benefits to you. Following are only some of the uses:

JAVA Sessions Customizations : Your can allow site visitors to customize the look and feel of your site, thus show each user a different view of your site. You can also show different content to different users depending on their preferences.

JAVA Sessions Security : You can allow membership based access to your site thus making sure that only members get to see special content on your site. After logging in you can identify members from non-members by setting an attribute on the user session to some value. Thus no need to log in again and again.

JAVA Sessions User Behavior : You can log user behavior like how many ad views have been shown to the user. If lot have been shown with no response from the user then it is time to change that ad. This is a great feature really, if you are into making an ad rotation software you can count how many ad views of which advertiser have been shown to the user and if user doesn't click through then better change that ad with some other one instead of wasting ad views of the same ad on this user.

JAVA Sessions HttpSession Interface Managing sessions has been made extremely easy by the Servlet API since there is just a single interface involved and that interface is HttpSession interface. You then invoke methods of this interface to interact with the user.

JAVA Sessions Methods of HttpSession Interface Before going into the details of using different methods of this interface, lets first see what are different methods available to us.

JAVA Sessions getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get and remove objects from a user session. We will see later how to use them.

JAVA Sessions getId() Every session created by the server has a unique 'id' associated with it in order to identify this session from other sessions. This method returns the 'id' of this session.

JAVA Sessions getCreationTime() Simple returns a long value indicating the date and time this session was created, meaning there by that you get the time this user first accessed your site.

JAVA Sessions getLastAccessedTime() Returns a long value indicating the last time user accessed any resource on this server.

JAVA Sessions getMaxInactiveInterval(), setMaxInactiveInterval() Return and set the maximum inactive interval in seconds for this session respectively. Note that every session has a maximum inactive interval during which if user doesn't make request to the server, his session is invalidated.

JAVA Sessions isNew() Returns a boolean value indicating if the session is new. It means that either it is the first page of the site user has hit so his session is new and has just been created or that user is not accepting cookies required for managing sessions so this value will then always return true.

JAVA Sessions invalidate() Simply invalidates a session. You can use this method on a 'logout' page allowing user to end his session. If after invalidation of his session user accesses some resource on the site then a new session will be created for it.

JAVA Sessions

2. The Session Tracking API Using sessions in servlets is quite straightforward, and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions. 2.1 Looking up the HttpSession object associated with the current request.HttpSession This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true togetSession. Thus, your first step usually looks like this: HttpSession session = request.getSession(true);

JAVA Sessions 2.2 Looking up Information Associated with a Session. HttpSession objects live on the server; they're just automatically associated with the requester by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects have a builtin data structure that let you store any number of keys and associated values. Here's one example, assuming ShoppingCart is some class you've defined yourself that stores information on items being purchased.

JAVA Sessions HttpSession session = request.getSession(true); ShoppingCart previousItems = (ShoppingCart)session.getAttribute("previousItem s"); if (previousItems != null) { doSomethingWith(previousItems); } else { previousItems = new ShoppingCart(...); doSomethingElseWith(previousItems); }

JAVA Sessions In most cases, you have a specific attribute name in mind, and want to find the value (if any) already associated with it. However, you can also discover all the attribute names in a given session by calling getAttributeNames, which returns an Enumeration.

JAVA Sessions 2.3 Associating Information with a Session As discussed in the previous section, you read information associated with a session by using getAttribute. To specify information, you setAttribute, supplying a key and a value. Note that setAttribute replaces any previous values. Sometimes that's what you want (as with the referringPage entry in the example below), but other times you want to retrieve a previous value and augment it (as with the previousItems entry below). Here's an example:

JAVA Sessions HttpSession session = request.getSession(true); session.setAttribute("referringPage", request.getHeader("Referer")); Enumeration previousItems = session.getAttribute("previousItems"); if (previousItems == null) { previousItems = new ShoppingCart(...); } String itemID = request.getParameter("itemID"); previousItems.addEntry(Catalog.getEntry(itemID)); // You still have to do setAttribute, not just modify //the cart, since // the cart may be new and thus not already stored in //the session. session.setAttribute("previousItems", previousItems);

JAVA Sessions Example Session Code package pack1; import java.io.Serializable; public class Counter implements Serializable {//N.B. classes that are used by your Session must implement Serializable private int count = 0; public int getCount() { return count; } public void increment() { count++; }

JAVA Sessions //TestSession Java file file imports package pack2; import pack1.Counter; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.*; import javax.servlet.http.*;

JAVA Sessions protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { HttpSession session = request.getSession(true); // declare out Counter object Counter counter; if(session.isNew()) { counter = new Counter(); session.setAttribute("counter", counter); } // incrementing page view count in our Counter object counter = ((Counter)session.getAttribute("counter")); counter.increment();

JAVA Sessions // retrieving session info long currentTime = System.currentTimeMillis(); long creationTime = session.getCreationTime(); long lastAccessed = session.getLastAccessedTime(); long maxInterval = session.getMaxInactiveInterval(); String sessionId = session.getId(); String mode = request.getParameter("mode");

JAVA Sessions // print content out.print(" "); out.print(" body, p { font-family:tahoma;"); out.print("font-size:12pt; } a { text-decoration:none;"); out.print("color:blue; } "); out.print(" ");

JAVA Sessions if(session.isNew()){ out.print(" New Session created. "); } else { out.print(" Old Session. "); out.print("Age : "); currentTime = System.currentTimeMillis(); out.print( (currentTime - creationTime) / ); out.print(" minutes. "); }

JAVA Sessions out.print(" You have visited this page : "); out.print( counter.getCount() ); out.print(" times. "); out.print("Created at : "); out.print( new Date(creationTime) ); out.print(" "); out.print("Last accessed : "); out.print( new Date(lastAccessed) ); out.print(" "); out.print("SessionID : "); out.print( sessionId );

JAVA Sessions out.print(" "); out.print("Note! Session will be inactivated after "); out.print("a period of inactivity of "); out.print( (maxInterval / 60) ); out.print(" minutes."); out.print(" ");

JAVA Sessions if( mode != null && mode.equals("invalidate")) { session.invalidate(); out.print("<a href=\"/sessionExample"); out.print("/TestSessionServlet\">"); out.print("Start New Session. "); } else { out.print("<a href=\"/sessionExample/"); out.print("TestSessionServlet?mode=invalidate \">"); out.print("Invalidate this Session. "); }

JAVA Sessions out.print(" "); } finally { out.close(); }

JAVA Sessions Nota Bene Primitive data types cannot be bound to user session : Most people make the mistake of binding primitive data types like int etc to the user session. This is not possible and you will get a translation-time error. The HttpSession interface only allows objects to be bound to the session.

JAVA Sessions Smaller the object the better it is : Since session may be required to be maintained across multiple servers, it is better that the size of objects bound to it remain small.

JAVA Sessions Make sure session level objects implement Serializable interface It is imperative that you understand this. All session level objects must implement Serializable interface because if your site spans multiple servers then the session level objects will not be ported to the other server. So in order to properly track user session along with all the bounded objects across multiple servers, your classes must implement Serializable interface.

JAVA Sessions