Session Tracking - Web Design and Development - Lecture Handouts, Lecture notes of Web Design and Development

Session Tracking, Store State Somewhere, PostNotes, Three Typical Solutions, Cookies, URL Rewriting, Hidden Fields, Potential Uses of Cookies, Looping down Cookies Array. Virtual University is one of best in Pakistan for distance education in science.

Typology: Lecture notes

2011/2012

Uploaded on 11/10/2012

taariq
taariq 🇵🇰

4.4

(16)

61 documents

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Handout 31
Web Design & Development CS-506
- 377 -
Lecture 31 Session Tracking
We have discussed the importance of session tracking in the previous handout. Now, we’ll
discover the basic techniques used for session tracking. Cookies are one of these techniques
and remain our focus in this handout. Cookies can be used to put small information on the
client’s machine and can be used for various other purposes besides session tracking. An
example of simple “Online Book Store”, using cookies, will also be surveyed.
As mentioned elsewhere, HTTP is a stateless protocol. Every request is considered
independent of every other request. But many applications need to maintain a conversational
state with the client. A shopping cart is a classical example of such conversational state.
Store State Somewhere
To maintain the conversational state, the straightforward approach is to store the state. But
where? These states either can be stored on server or on client. However, both options have
their merits and demerits. Let’s cast a glance on these options:
Storing state on server side makes server really complicated as states needed to be stored for
each client. Some one can imagine how much space and processing is required in this
scenario as some web servers are hit more than hundred times in a second. E.g. Google,
Yahoo etc.
What if states are stored on client side in order to maintain a conversation? Do all the clients
permit you doing that? What if client (user) wiped out these states from the machine?
Concluding this discussion, state is stored neither completely on server side nor on client.
States are maintained by the mutual cooperation of both client & server. Generally modern
servers give the capability to store state on the server side and some information (e.g. client
ID/state ID) passed from the client will relate each client with its corresponding state.
Post–Notes
In order to maintain the conversational state, server puts little notes (some text, values etc) on
the client slide. When client submits the next form, it also unknowingly submits these little
notes. Server reads these notes and able to recall who the client is.
Three Typical Solutions
Three typical solutions come across to accomplish session tracking. These are:
1. Cookies
2. URL Rewriting
3. Hidden Fields
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Session Tracking - Web Design and Development - Lecture Handouts and more Lecture notes Web Design and Development in PDF only on Docsity!

Web Design & Development CS-

Lecture 31

Session Tracking

We have discussed the importance of session tracking in the previous handout. Now, we’ll

discover the basic techniques used for session tracking. Cookies are one of these techniques

and remain our focus in this handout. Cookies can be used to put small information on the

client’s machine and can be used for various other purposes besides session tracking. An

example of simple “Online Book Store”, using cookies, will also be surveyed.

As mentioned elsewhere, HTTP is a stateless protocol. Every request is considered

independent of every other request. But many applications need to maintain a conversational

state with the client. A shopping cart is a classical example of such conversational state.

Store State Somewhere

To maintain the conversational state, the straightforward approach is to store the state. But

where? These states either can be stored on server or on client. However, both options have

their merits and demerits. Let’s cast a glance on these options:

Storing state on server side makes server really complicated as states needed to be stored for

each client. Some one can imagine how much space and processing is required in this

scenario as some web servers are hit more than hundred times in a second. E.g. Google,

Yahoo etc.

What if states are stored on client side in order to maintain a conversation? Do all the clients

permit you doing that? What if client (user) wiped out these states from the machine?

Concluding this discussion, state is stored neither completely on server side nor on client.

States are maintained by the mutual cooperation of both client & server. Generally modern

servers give the capability to store state on the server side and some information (e.g. client

ID/state ID) passed from the client will relate each client with its corresponding state.

Post–Notes

In order to maintain the conversational state, server puts little notes (some text, values etc) on

the client slide. When client submits the next form, it also unknowingly submits these little

notes. Server reads these notes and able to recall who the client is.

Three Typical Solutions

Three typical solutions come across to accomplish session tracking. These are:

1. Cookies

2. URL Rewriting

3. Hidden Fields

Web Design & Development CS-

Cookies

What a cookie is?

Don’t be tempted? These are not, what you might be thinking off. In fact, in computer

terminology, “a cookie is a piece of text that a web server can store on a client’s (user) hard

disk”.

Cookies allow the web sites to store information on a client machine and later retrieve it. The

pieces of information are stored as name-value pair on the client. Later while reconnecting to

the same site (or same domain depending upon the cookie settings), client returns the same

name-value pair to the server.

Cookie’s Voyage

To reveal the mechanism of cookies, let’s take an example. We are assuming here that the

web application we are using will set some cookies

ƒ If you type URL of a Web site into your browser, your browser sends a request for

that web page

− For example, when you type www.amazon.com a request is send to the Amazon’s

server

ƒ Before sending a request, browser looks for cookie files that amazon has set

− If browser finds one or more cookie files related to amazon, it will send it along

with the request

− If not, no cookie data will be sent with the request

ƒ Amazaon web server receives the request and examines the request for cookies

− If cookies are received, amazon can use them

− If no cookie is received, amazon knows that you have not visited before or the

cookies that were previously set got expired.

− Server creates a new cookie and send to your browser in the header of HTTP

Response so that it can be saved on the client machine.

Potential Uses of Cookies

Whether cookies have more pros or cons is arguable. However, cookies are helpful in the

following situations

ƒ Identifying a user during an e-commerce session. For example, this book is added into

shopping cart by this client.

Web Design & Development CS-

Reading Cookies from the Client

To read the cookies that come back from the client, following steps are generally followed.

1. Reading incoming cookies

To read incoming cookies, get them from the request object of the

HttpServeltRequest by calling following method

Cookie cookies[] = request.getCookies();

This call returns an array of Cookies object corresponding to the name & values

that came in the HTT P request header.

2. Looping down Cookies Array

Once you have an array of cookies, you can iterate over it. Two important methods of

Cookie class are getName() & getValue(). These are used to retrieve cookie

name and value respectively.

// looping down the whole cookies array

for(int i=0; i

Web Design & Development CS-

Example Code1: Repeat Visitor

In the example below, servlet checks for a unique cookie, named “repeat”. If the cookie is

present, servlet displays “Welcome Back”. Absence of cookie indicates that the user is

visiting this site for the first time thus servlet displays a message “Welcome Aboard”.

This example contains only one servlet “RepeatVisitorServlet.java” and its code

is given below. A code snippet of web.xml is also accompanied.

Note: As a reminder , all these examples are built using netBeans4.1. This IDE will write

web.xml for you. However, here it is given for your reference purpose only, or for those

which are not using any IDE to strengthen their concepts

RepeatVisitorServlet.java

import java.io.; import java.net.; import javax.servlet.; import javax.servlet.http.;

public class RepeatVisitorServlet extends HttpServlet {

// Handles the HTTP GET method. protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

// Handles the HTTP POST method. protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

// called from both doGet() & doPost() protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

// writing html out.println(""); out.println("");

Web Design & Development CS-

web.xml

RepeatVisitorServlet RepeatVisitorServlet

RepeatVisitorServlet /repeatexample

Output

On first time visiting this URL, an output similar to the one given below would be displayed

On refreshing this page or revisiting it within an hour (since the age of cookie was set to 60

mins), following output should be expected.

Web Design & Development CS-

Example Code2: Online Book Store using cookies

A scale down version of online book store is going to be built using cookies. For the first

time, cookies will be used to maintain the session.

Three books will be displayed to the user along with check boxes. User can select any check

box to add the book in the shopping cart. The heart of the application is, it remembers the

books previously selected by the user.

The following figure will help you understand the theme of this example. Books displayed

under the heading of “You have selected the following books” were added to cart one after

another. The important thing is server that remembers the previously added books by the

same user and thus maintains the session. Session management is accomplished using

cookies.

Web Design & Development CS-

response.setContentType("text/html;charset=UTF-8");

// declaring user's HashMap HashMap sessionInfo = null; String sID = "";

// method findCookie is used to determine whether browser // has send any cookie named "JSESSIONID" Cookie c = findCookie(request);

// if no cookies named "JSESSIONID" is recieved, means that // user is visiting the site for the first time. if (c == null) {

// make a unique string sID = makeUniqueString();

// creating a HashMap where books selected by the // user will be stored sessionInfo = new HashMap();

// add the user's HashMap (sessionInfo) into the // globalMap against unique string i.e. sID globalMap.put(sID, sessionInfo);

// create a cookie named "JSESSIONID" alongwith // value of sID i.e. unique string Cookie sessionCookie = new Cookie("JSESSIONID", sID);

// add the cookie to the response response.addCookie(sessionCookie);

} else {

// if cookie is found named "JSESSIONID", // retrieve a HashMap from the globalMap against // cookie value i.e. unique string which is your //sessionID sessionInfo = (HashMap) globalMap.get( c.getValue() ); }

PrintWriter out = response.getWriter();

out.println(""); out.println(""); out.println("Shooping Cart Example"); out.println(""); out.println(""); out.println("Online Book Store");

String url = "http://localhost:8084/cookiesessionex/shoppingcartex";

// user will submit the from to the same servlet

Web Design & Development CS-

out.println("" + "" + " java core servlts" + ""+

“" + " java how to program" + ""+

"" + " java complete reference" + ""+

"" + "" );

out.println(""); out.println("You have selected followig books"); out.println("");

//reteriving params of check boxes String fBook = request.getParameter("firstCB"); String sBook = request.getParameter("secondCB"); String tBook = request.getParameter("thirdCB");

// if first book is selected then add it to // user's HashMap i.e. sessionInfo if ( fBook != null && fBook.equals("firstCB") ) { sessionInfo.put("firstCB", "java core servlets"); }

// if second book is selected then add it to // user's HashMap i.e. sessionInfo if (sBook != null && sBook.equals("secondCB")){ sessionInfo.put("secondCB", "java how to program"); }

// if third book is selected then add it to // user's HashMap i.e. sessionInfo if (tBook != null && tBook.equals("thirdCB")){ sessionInfo.put("thirdCB", "java complete reference"); }

// used to display the books currently stored in // the user's HashMap i.e. sessionInfo printSessionInfo(out, sessionInfo);

out.println(""); out.println("");

out.close();

} // end processRequest()

Web Design & Development CS-

} // end ShoppingCartServlet

Web Design & Development CS-

web.xml

ShoppingCart ShoppingCartServlet

ShoppingCart /shoppingcartex