SlideShare a Scribd company logo
1
SESSION TRACKING
WHAT IS A
SESSION ?
2
•A session can be defined as a series of related
interactions between a single client and the Web
server over a period of time.
•To track data among requests in a session is
known as session tracking.
Session Tracking 3
SESSION TRACKING AND E-
COMMERCE
 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?
SESSION TRACKING WITH
SERVLETS
•HTTP is a stateless protocol.
•We must have each user introduce themselves in some
way.
•We’ll look at traditional session tracking and then look
at the Session Tracking API.
TRADITIONAL SESSION TRACKING
GSIAE-CommerceTechnologiesII
• Hidden Form fields
•URL Rewriting
•User Authorization
• Persistent cookies
SESSION TRACKING USING HIDDEN
VALUES
6
You can track session by passing data from the servlet to the client
as hidden value in a dynamically generated HTML form by
including a field like this:
<input type=”hidden” name=”lastName” value=”Smith”>
So the next request will submit the data back to the servlet. The
servlet retrieves this hidden value just like any other parameter
value using the getParameter method.
EXAMPLE: USING HIDDEN VALUES IN
THE REGISTRATION FORM
7
•This example creates a servlet that processes a registration
form.
•The client first submits the form using the GET method.
•The server collects the data in the form, displays the data
to the client, and asks the client for confirmation.
•The client confirms it by submitting the request with the
hidden values using the POST method.
• Finally, the servlet writes the data to a database.
EXAMPLE: USING HIDDEN VALUES IN
THE REGISTRATION FORM, CONT.
8
RegistrationRegistration RunRun
Session Tracking 9
HIDDEN FORM FIELDS
 Idea:
<INPUT TYPE="HIDDEN" NAME="session"
VALUE="...">
 Advantage
 Works even if cookies are disabled or unsupported
 Disadvantages
 Lots of tedious processing
 All pages must be the result of form submissions
Session Tracking 10
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
USER AUTHORIZATION
• The web server requests the user name and password.
The information is available to any servlet that needs it.
• The browser resends the name and password with each
subsequent request.
• Data about the user and the user’s state can be saved in a
shared object.
SHARED OBJECTS
• A convenient way to store data associated with a user.
•There are likely to be many servlets running.
• They can collaborate through a shared object.
• Only one instance of the shared object should exist.
• It has to be available (in the classpath) of the servlets
that needs it.
• It will be used by several threads and therefore should
protect itself against simultaneous access.
• We’ll look at a shared object and two servlets that use it.
VISITTRACKER.JAVA
// Servlet collaboration can be done through a shared object.
// Any servlet has access to this object and it only has one
// instance.
// It maintains a hash table of names and dates.
// Sections of code that must not be executed simultaneously
// are called critical sections. Java provides the synchronized
// keyword to protect these critical sections. For a synchronized
// instance method, Java obtains an exclusive lock on the class
// instance.
import java.util.*;
public class VisitTracker {
private Map nameDatePairs;
private static VisitTracker instance = new VisitTracker();
private VisitTracker() { // private constructor
nameDatePairs = new HashMap();
}
public static VisitTracker getInstance() { return
instance; }
synchronized public void addVisit(String userName) {
nameDatePairs.put(userName, new Date());
}
GSIAE-CommerceTechnologiesII
synchronized public Date lastVisit(String name) {
Date d = (Date)nameDatePairs.get(name);
return d;
}
}
COOKIES
• A cookie is a bit of information sent by a web server
to a browser that can later be read back from that browser.
• The server can take that bit of information and use it as a
key to recover information about prior visits. This
information may be in a database or a shared object.
• Cookies are read from the request object by calling
getCookies() on the request object.
• Cookies are placed in the browser by calling addCookie()
on the response object.
SESSION TRACKING USING
COOKIES
17
•You can track sessions using cookies.
•Cookies are small text files that store sets of name=value pairs on
the disk in the client’s computer.
•Cookies are sent from the server through the instructions in the
header of the HTTP response.
•The instructions tell the browser to create a cookie with a given
name and its associated value.
•If the browser already has the cookie with the key name, the value
will be updated.
•The browser will then send the cookie with any request submitted
to the same server.
•Cookies can have expiration dates set, after which the cookies will
not be sent to the server.
USING COOKIES
// CookieDemo.java
// This servlet uses a cookie to determine when the
// last visit by this browser occurred. It makes use of
// the VisitTracker object.
// Cookies normally expire as soon as the browser exits.
// We want the cookie to last one year and so we use
// setMaxAge(seconds) on the cookie.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieDemo extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
Cookie[] c = req.getCookies();
// If this person has been here before then we should have
// a cookiedemouser field assigned to a unique id.
String id = null;
if (c!=null) { // we may have the cookie we are after
for (int i=0;i<c.length;i++) {
if (c[i].getName().equals("cookiedemouser")) {
id = c[i].getValue();
}
break;
}
}
if (id == null) {
// They have not been here before and need a
// cookie. We get a unique string and make sure
// it is of the 'query string' form.
String uid = new java.rmi.server.UID().toString();
id = java.net.URLEncoder.encode(uid);
Cookie oreo = new Cookie("cookiedemouser",id);
oreo.setMaxAge(60*60*24*365);
res.addCookie(oreo);
}
VisitTracker visit = VisitTracker.getInstance();
Date last = visit.lastVisit(id);
if(last == null) out.println("Welcome, you were never here
before");
else out.println("Your last visit was on " + last);
visit.addVisit(id);
}
}
Session Tracking 22
ROLLING YOUR OWN SESSION
TRACKING: COOKIES
 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);
 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
SESSION TRACKING USING THE
SERVLET API
23
•The problems of session tracking with hidden data and cookies
are that data are not secured and difficult to deal with large set of
data.
•Java servlet API provides a session tracking tool, which enables
tracking of a large set of data. Data can be stored as objects. Data
are kept on the server side so they are secure.
THE HTTPSESSION CLASS
24
•To use the Java servlet API for session tracking, first create a
session object using the getSession method in the
HttpServletRequest interface like this:
HttpSession session = request.getSession(true);
•This obtains the session or creates a new session if the client
does not have a session on the server.
•The HttpSession class provides the methods for reading and
storing data to the session, and for manipulating the session.
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 ) stores values
◦ getAttribute (getValue) retrieves values
25Session Tracking
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);
26Session Tracking
HTTPSESSION METHODS
 getAttribute (getValue)
◦ Extracts a previously stored value from a session
object. Returns null if no value is associated with given
name.
 setAttribute (putValue)
◦ Associates a value with a name. Monitor changes:
values implement HttpSessionBindingListener.
 removeAttribute (removeValue )
◦ Removes values associated with name.
 getAttributeNames (getValueNames)
◦ Returns names of all attributes in the session.
 getId
◦ Returns the unique identifier.
27Session Tracking
HTTPSESSION METHODS
(CONTINUED)
 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
28Session Tracking
A 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);
29Session Tracking
FIRST VISIT TO SHOWSESSION
SERVLET
30Session Tracking
ELEVENTH VISIT TO SHOWSESSION
SERVLET
31Session Tracking
SESSION TRACKING AND SHOPPING
CARTS
32Session Tracking
SESSION TRACKING AND SHOPPING
CARTS (CONTINUED)
33Session Tracking
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 is
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
34Session Tracking

More Related Content

PPTX
01 session tracking
PDF
Spring4 security
PDF
Servlet sessions
PPTX
Advance Java
PDF
Node.js 與 google cloud storage
PDF
Dandelion 0.10.0
PPTX
Final microsoft cloud summit - windows azure building block services
PDF
08 session-tracking
01 session tracking
Spring4 security
Servlet sessions
Advance Java
Node.js 與 google cloud storage
Dandelion 0.10.0
Final microsoft cloud summit - windows azure building block services
08 session-tracking

What's hot (20)

TXT
Birhanu distributive assignment
PPTX
Azure Table Storage: The Good, the Bad, the Ugly (15 min. lightning talk)
PDF
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
PPTX
Soa development using javascript
PDF
JavaFest. Nanne Baars. Web application security for developers
PPTX
Ch05 state management
DOCX
Experienced Selenium Interview questions
PPTX
Web Technologies - forms and actions
PPTX
Introduction to ASP.Net Viewstate
PPTX
Beyond the page
PDF
C fowler azure-dojo
PPT
Waffle at NYCJavaSig
PDF
Talk about html5 security
PDF
Simple Web Development in Java
PPTX
Architecting Secure and Compliant Applications with MongoDB
PPT
Lecture 2
PDF
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
PPT
State management in ASP.NET
PDF
Nuxeo - OpenSocial
PDF
mDevCamp - The Best from Google IO
Birhanu distributive assignment
Azure Table Storage: The Good, the Bad, the Ugly (15 min. lightning talk)
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
Soa development using javascript
JavaFest. Nanne Baars. Web application security for developers
Ch05 state management
Experienced Selenium Interview questions
Web Technologies - forms and actions
Introduction to ASP.Net Viewstate
Beyond the page
C fowler azure-dojo
Waffle at NYCJavaSig
Talk about html5 security
Simple Web Development in Java
Architecting Secure and Compliant Applications with MongoDB
Lecture 2
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
State management in ASP.NET
Nuxeo - OpenSocial
mDevCamp - The Best from Google IO
Ad

Viewers also liked (9)

PDF
Lecture 3: Servlets - Session Management
PPTX
SCWCD : Session management : CHAP : 6
PPT
Hearbs drugs interaction
PPTX
Herb drug interaction
PPTX
Pharmacovigilance for ASU Drugs
PPTX
HERBAL PHARMACOVIGILANCE ppt - Copy
PPT
Jsp ppt
PPTX
Herb drug interaction ppt by rupesh kumar
PDF
Rasashastra ppt – part 2 - By Prof.Dr.R.R.deshpande
Lecture 3: Servlets - Session Management
SCWCD : Session management : CHAP : 6
Hearbs drugs interaction
Herb drug interaction
Pharmacovigilance for ASU Drugs
HERBAL PHARMACOVIGILANCE ppt - Copy
Jsp ppt
Herb drug interaction ppt by rupesh kumar
Rasashastra ppt – part 2 - By Prof.Dr.R.R.deshpande
Ad

Similar to Ecom2 (20)

PPTX
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
PPTX
19_JavaScript - Storage_Cookies-tutorial .pptx
PPTX
19_JavaScript - Storage_Cookies_students.pptx
PPTX
Using cookies and sessions
PPTX
Chapter 8 part1
PDF
Jsp session tracking
PPTX
Advance java session 7
PDF
08 session-tracking
PPTX
SessionTrackServlets.pptx
PPTX
Authentication in Svelte using cookies.pptx
PDF
PHP-Cookies-Sessions.pdf
PPT
Php ssession - cookies -introduction
PDF
Sea surfing in asp.net mvc
PPT
Java - Servlet - Mazenet Solution
PPTX
J2EE : Java servlet and its types, environment
PDF
Bt0083 server side programing
PPTX
Ch09 -Managing State and Information Security
PPTX
Event Handling -_GET _ POSTimplementation.pptx
PPSX
Sessions and cookies
PPTX
Session And Cookies In Servlets - Java
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies_students.pptx
Using cookies and sessions
Chapter 8 part1
Jsp session tracking
Advance java session 7
08 session-tracking
SessionTrackServlets.pptx
Authentication in Svelte using cookies.pptx
PHP-Cookies-Sessions.pdf
Php ssession - cookies -introduction
Sea surfing in asp.net mvc
Java - Servlet - Mazenet Solution
J2EE : Java servlet and its types, environment
Bt0083 server side programing
Ch09 -Managing State and Information Security
Event Handling -_GET _ POSTimplementation.pptx
Sessions and cookies
Session And Cookies In Servlets - Java

Recently uploaded (20)

PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Current and future trends in Computer Vision.pptx
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
PPT on Performance Review to get promotions
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPT
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PPTX
Fundamentals of Mechanical Engineering.pptx
PPTX
Nature of X-rays, X- Ray Equipment, Fluoroscopy
PDF
737-MAX_SRG.pdf student reference guides
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PDF
COURSE DESCRIPTOR OF SURVEYING R24 SYLLABUS
UNIT 4 Total Quality Management .pptx
Current and future trends in Computer Vision.pptx
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PPT on Performance Review to get promotions
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
Fundamentals of safety and accident prevention -final (1).pptx
Fundamentals of Mechanical Engineering.pptx
Nature of X-rays, X- Ray Equipment, Fluoroscopy
737-MAX_SRG.pdf student reference guides
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
R24 SURVEYING LAB MANUAL for civil enggi
Automation-in-Manufacturing-Chapter-Introduction.pdf
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Exploratory_Data_Analysis_Fundamentals.pdf
COURSE DESCRIPTOR OF SURVEYING R24 SYLLABUS

Ecom2

  • 2. WHAT IS A SESSION ? 2 •A session can be defined as a series of related interactions between a single client and the Web server over a period of time. •To track data among requests in a session is known as session tracking.
  • 3. Session Tracking 3 SESSION TRACKING AND E- COMMERCE  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?
  • 4. SESSION TRACKING WITH SERVLETS •HTTP is a stateless protocol. •We must have each user introduce themselves in some way. •We’ll look at traditional session tracking and then look at the Session Tracking API.
  • 5. TRADITIONAL SESSION TRACKING GSIAE-CommerceTechnologiesII • Hidden Form fields •URL Rewriting •User Authorization • Persistent cookies
  • 6. SESSION TRACKING USING HIDDEN VALUES 6 You can track session by passing data from the servlet to the client as hidden value in a dynamically generated HTML form by including a field like this: <input type=”hidden” name=”lastName” value=”Smith”> So the next request will submit the data back to the servlet. The servlet retrieves this hidden value just like any other parameter value using the getParameter method.
  • 7. EXAMPLE: USING HIDDEN VALUES IN THE REGISTRATION FORM 7 •This example creates a servlet that processes a registration form. •The client first submits the form using the GET method. •The server collects the data in the form, displays the data to the client, and asks the client for confirmation. •The client confirms it by submitting the request with the hidden values using the POST method. • Finally, the servlet writes the data to a database.
  • 8. EXAMPLE: USING HIDDEN VALUES IN THE REGISTRATION FORM, CONT. 8 RegistrationRegistration RunRun
  • 9. Session Tracking 9 HIDDEN FORM FIELDS  Idea: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">  Advantage  Works even if cookies are disabled or unsupported  Disadvantages  Lots of tedious processing  All pages must be the result of form submissions
  • 10. Session Tracking 10 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
  • 11. USER AUTHORIZATION • The web server requests the user name and password. The information is available to any servlet that needs it. • The browser resends the name and password with each subsequent request. • Data about the user and the user’s state can be saved in a shared object.
  • 12. SHARED OBJECTS • A convenient way to store data associated with a user. •There are likely to be many servlets running. • They can collaborate through a shared object. • Only one instance of the shared object should exist. • It has to be available (in the classpath) of the servlets that needs it. • It will be used by several threads and therefore should protect itself against simultaneous access. • We’ll look at a shared object and two servlets that use it.
  • 13. VISITTRACKER.JAVA // Servlet collaboration can be done through a shared object. // Any servlet has access to this object and it only has one // instance. // It maintains a hash table of names and dates. // Sections of code that must not be executed simultaneously // are called critical sections. Java provides the synchronized // keyword to protect these critical sections. For a synchronized // instance method, Java obtains an exclusive lock on the class // instance.
  • 14. import java.util.*; public class VisitTracker { private Map nameDatePairs; private static VisitTracker instance = new VisitTracker(); private VisitTracker() { // private constructor nameDatePairs = new HashMap(); } public static VisitTracker getInstance() { return instance; } synchronized public void addVisit(String userName) { nameDatePairs.put(userName, new Date()); }
  • 15. GSIAE-CommerceTechnologiesII synchronized public Date lastVisit(String name) { Date d = (Date)nameDatePairs.get(name); return d; } }
  • 16. COOKIES • A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. • The server can take that bit of information and use it as a key to recover information about prior visits. This information may be in a database or a shared object. • Cookies are read from the request object by calling getCookies() on the request object. • Cookies are placed in the browser by calling addCookie() on the response object.
  • 17. SESSION TRACKING USING COOKIES 17 •You can track sessions using cookies. •Cookies are small text files that store sets of name=value pairs on the disk in the client’s computer. •Cookies are sent from the server through the instructions in the header of the HTTP response. •The instructions tell the browser to create a cookie with a given name and its associated value. •If the browser already has the cookie with the key name, the value will be updated. •The browser will then send the cookie with any request submitted to the same server. •Cookies can have expiration dates set, after which the cookies will not be sent to the server.
  • 18. USING COOKIES // CookieDemo.java // This servlet uses a cookie to determine when the // last visit by this browser occurred. It makes use of // the VisitTracker object. // Cookies normally expire as soon as the browser exits. // We want the cookie to last one year and so we use // setMaxAge(seconds) on the cookie. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;
  • 19. public class CookieDemo extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); Cookie[] c = req.getCookies(); // If this person has been here before then we should have // a cookiedemouser field assigned to a unique id. String id = null;
  • 20. if (c!=null) { // we may have the cookie we are after for (int i=0;i<c.length;i++) { if (c[i].getName().equals("cookiedemouser")) { id = c[i].getValue(); } break; } }
  • 21. if (id == null) { // They have not been here before and need a // cookie. We get a unique string and make sure // it is of the 'query string' form. String uid = new java.rmi.server.UID().toString(); id = java.net.URLEncoder.encode(uid); Cookie oreo = new Cookie("cookiedemouser",id); oreo.setMaxAge(60*60*24*365); res.addCookie(oreo); } VisitTracker visit = VisitTracker.getInstance(); Date last = visit.lastVisit(id); if(last == null) out.println("Welcome, you were never here before"); else out.println("Your last visit was on " + last); visit.addVisit(id); } }
  • 22. Session Tracking 22 ROLLING YOUR OWN SESSION TRACKING: COOKIES  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);  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
  • 23. SESSION TRACKING USING THE SERVLET API 23 •The problems of session tracking with hidden data and cookies are that data are not secured and difficult to deal with large set of data. •Java servlet API provides a session tracking tool, which enables tracking of a large set of data. Data can be stored as objects. Data are kept on the server side so they are secure.
  • 24. THE HTTPSESSION CLASS 24 •To use the Java servlet API for session tracking, first create a session object using the getSession method in the HttpServletRequest interface like this: HttpSession session = request.getSession(true); •This obtains the session or creates a new session if the client does not have a session on the server. •The HttpSession class provides the methods for reading and storing data to the session, and for manipulating the session.
  • 25. 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 ) stores values ◦ getAttribute (getValue) retrieves values 25Session Tracking
  • 26. 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); 26Session Tracking
  • 27. HTTPSESSION METHODS  getAttribute (getValue) ◦ Extracts a previously stored value from a session object. Returns null if no value is associated with given name.  setAttribute (putValue) ◦ Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener.  removeAttribute (removeValue ) ◦ Removes values associated with name.  getAttributeNames (getValueNames) ◦ Returns names of all attributes in the session.  getId ◦ Returns the unique identifier. 27Session Tracking
  • 28. HTTPSESSION METHODS (CONTINUED)  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 28Session Tracking
  • 29. A 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); 29Session Tracking
  • 30. FIRST VISIT TO SHOWSESSION SERVLET 30Session Tracking
  • 31. ELEVENTH VISIT TO SHOWSESSION SERVLET 31Session Tracking
  • 32. SESSION TRACKING AND SHOPPING CARTS 32Session Tracking
  • 33. SESSION TRACKING AND SHOPPING CARTS (CONTINUED) 33Session Tracking
  • 34. 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 is 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 34Session Tracking