SlideShare a Scribd company logo
1 of 34
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

What's hot

Birhanu distributive assignment
Birhanu distributive assignmentBirhanu distributive assignment
Birhanu distributive assignmentuniversity
 
Azure Table Storage: The Good, the Bad, the Ugly (15 min. lightning talk)
Azure Table Storage: The Good, the Bad, the Ugly (15 min. lightning talk)Azure Table Storage: The Good, the Bad, the Ugly (15 min. lightning talk)
Azure Table Storage: The Good, the Bad, the Ugly (15 min. lightning talk)Sirar Salih
 
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingBDD, ATDD, Page Objects: The Road to Sustainable Web Testing
BDD, ATDD, Page Objects: The Road to Sustainable Web TestingJohn Ferguson Smart Limited
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascriptDsixE Inc
 
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developersJavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developersFestGroup
 
Experienced Selenium Interview questions
Experienced Selenium Interview questionsExperienced Selenium Interview questions
Experienced Selenium Interview questionsarchana singh
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojosdeconf
 
Talk about html5 security
Talk about html5 securityTalk about html5 security
Talk about html5 securityHuang Toby
 
Simple Web Development in Java
Simple Web Development in JavaSimple Web Development in Java
Simple Web Development in JavaVincent Tencé
 
Architecting Secure and Compliant Applications with MongoDB
Architecting Secure and Compliant Applications with MongoDB        Architecting Secure and Compliant Applications with MongoDB
Architecting Secure and Compliant Applications with MongoDB MongoDB
 
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenOAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenCodemotion
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NETOm Vikram Thapa
 
Nuxeo - OpenSocial
Nuxeo - OpenSocialNuxeo - OpenSocial
Nuxeo - OpenSocialThomas Roger
 
mDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOmDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOondraz
 

What's hot (20)

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

Viewers also liked

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6Ben Abdallah Helmi
 
Hearbs drugs interaction
Hearbs drugs interactionHearbs drugs interaction
Hearbs drugs interactionBidhan Mahajon
 
Herb drug interaction
Herb drug interactionHerb drug interaction
Herb drug interactionNITIN KANWALE
 
HERBAL PHARMACOVIGILANCE ppt - Copy
HERBAL PHARMACOVIGILANCE ppt - CopyHERBAL PHARMACOVIGILANCE ppt - Copy
HERBAL PHARMACOVIGILANCE ppt - CopyArpita Verma
 
Rasashastra ppt – part 2 - By Prof.Dr.R.R.deshpande
Rasashastra ppt – part 2  - By Prof.Dr.R.R.deshpandeRasashastra ppt – part 2  - By Prof.Dr.R.R.deshpande
Rasashastra ppt – part 2 - By Prof.Dr.R.R.deshpanderajendra deshpande
 

Viewers also liked (9)

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6
 
Hearbs drugs interaction
Hearbs drugs interactionHearbs drugs interaction
Hearbs drugs interaction
 
Herb drug interaction
Herb drug interactionHerb drug interaction
Herb drug interaction
 
Pharmacovigilance for ASU Drugs
Pharmacovigilance for ASU DrugsPharmacovigilance for ASU Drugs
Pharmacovigilance for ASU Drugs
 
HERBAL PHARMACOVIGILANCE ppt - Copy
HERBAL PHARMACOVIGILANCE ppt - CopyHERBAL PHARMACOVIGILANCE ppt - Copy
HERBAL PHARMACOVIGILANCE ppt - Copy
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Herb drug interaction ppt by rupesh kumar
Herb drug interaction ppt by rupesh kumarHerb drug interaction ppt by rupesh kumar
Herb drug interaction ppt by rupesh kumar
 
Rasashastra ppt – part 2 - By Prof.Dr.R.R.deshpande
Rasashastra ppt – part 2  - By Prof.Dr.R.R.deshpandeRasashastra ppt – part 2  - By Prof.Dr.R.R.deshpande
Rasashastra ppt – part 2 - By Prof.Dr.R.R.deshpande
 

Similar to Ecom2

19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptxssuser4a97d3
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptxVatsalJain39
 
Using cookies and sessions
Using cookies and sessionsUsing cookies and sessions
Using cookies and sessionsNuha Noor
 
Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session trackingrvarshneyp
 
Advance java session 7
Advance java session 7Advance java session 7
Advance java session 7Smita B Kumar
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptxRanjeet Reddy
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfHumphreyOwuor1
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
Sea surfing in asp.net mvc
Sea surfing in asp.net mvcSea surfing in asp.net mvc
Sea surfing in asp.net mvcmagda3695
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionMazenetsolution
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Ch09 -Managing State and Information Security
Ch09 -Managing State and Information SecurityCh09 -Managing State and Information Security
Ch09 -Managing State and Information Securitydcomfort6819
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaJainamParikh3
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfKALAISELVI P
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 

Similar to Ecom2 (20)

19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
 
19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx19_JavaScript - Storage_Cookies_students.pptx
19_JavaScript - Storage_Cookies_students.pptx
 
Using cookies and sessions
Using cookies and sessionsUsing cookies and sessions
Using cookies and sessions
 
Chapter 8 part1
Chapter 8   part1Chapter 8   part1
Chapter 8 part1
 
Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session tracking
 
Advance java session 7
Advance java session 7Advance java session 7
Advance java session 7
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptx
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
Sea surfing in asp.net mvc
Sea surfing in asp.net mvcSea surfing in asp.net mvc
Sea surfing in asp.net mvc
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Ch09 -Managing State and Information Security
Ch09 -Managing State and Information SecurityCh09 -Managing State and Information Security
Ch09 -Managing State and Information Security
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
 
Servlets
ServletsServlets
Servlets
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 

Recently uploaded

BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxNiranjanYadav41
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectErbil Polytechnic University
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 

Recently uploaded (20)

BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptx
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction Project
 
Designing pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptxDesigning pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptx
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 

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