IP Topic5 Session Tracking
IP Topic5 Session Tracking
INTERNET PROGRAMMING
TOPIC 5 –
JAVA WEB SESSION TRACKING
Knowledge
• Describe the way HTTP works without session tracking.
• Describe the way cookies and HTTP session are used for session tracking.
• Describe the way URL encoding is used for session tracking.
• Distinguish between persistent cookies and per-session cookies.
• Distinguish between the use of URL rewriting and the use of hidden fields as
ways to implement parameter passing.
• Describe the way HTTP session in servlet and JSP are used for session tracking.
2
Session Tracking
• HTTP is a stateless protocol which means each request is considered as the new
request. Once a browser makes a request, it drops the connection to the server. So, to
maintain state, a web application must use session tracking.
3
Why session tracking is difficult with HTTP?
4
How Java keep tracks of session?
5
How Java keep tracks of session?
• A browser on a client request a JSP or servlet from the web server, which passes the
request to the servlet engine.
• Then, the servlet engine checks if the request includes an ID for the Java session.
• If it doesn’t, the servlet engine creates a unique ID for the session plus a session
object that can be used to store the data for the session.
• From that point on, the web server uses the session ID to relate each browser request
to the session object, even though the server still drops the HTTP connection after
returning each page.
6
Example of session tracking
For example, a shopping cart module should know: who is sending the request to
add an item, in which cart the item has to be added or who is sending checkout
request. So that, it can charge the amount to the correct client.
7
Techniques for Session Tracking
01 Cookies
Hidden Field 02
03 URL Rewriting
HTTP Session 04
8
Cookies
• A cookie is a small piece of information that is persisted between the multiple client
requests.
• A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
Cookies
• By default, the servlet API uses a cookie to store a session ID in each browser.
Then, the browser passes the cookie to the server with each request. To store the data
for each session, the server creates a session object.
9
How cookies work?
• A cookie is a name/value pair that is stored in a browser.
• On the server, a web application creates a cookie and sends it to the
browser.
• On the client, the browser saves the cookie and sends it back to the
Cookies
10
Typical uses for cookies
• To allow users to skip login and registration forms that gather data like
user name, password, address, or credit card data.
• To customize pages that display information like weather reports, sports
Cookies
11
Cookies
Constructor of the Cookie class
Constructor Description
Cookie(String name, String value) Creates a cookie with the
specified name and value.
Cookies
Method Description
setMaxAge
(int maxAgeInSeconds)
To create a persistent cookie, set the
cookie’s maximum age to a positive
number. To create a per- session
cookie, set the cookie’s maximum age
Cookies
13
Code that creates and sets a cookie
14
A JSP that shows all cookies for the current server
Cookies
15
JSP code that displays all cookies
<%
Cookie[] cookies = request.getCookies();
for (Cookie c : cookies)
{
%>
Cookies
<tr>
<td align="right"><%= c.getName() %></td>
<td><%= c.getValue() %></td>
</tr>
<%
}
%>
16
Servlet code that deletes all persistent cookies
17
Four methods of the Cookie class
• setPath(String path)
• setDomain(String domainPattern)
•
Cookies
setSecure(boolean flag)
• setVersion(int version)
Note
• All of these set methods have corresponding get
methods.
18
A utility class that gets the value of a cookie
package util;import
javax.servlet.http.*;
public class CookieUtil
{
public static String
getCookieValue( Cookie[] cookies,
String cookieName)
Cookies
{
String cookieValue = "";
Cookie cookie;
if (cookies != null)
{
for (int i=0; i<cookies.length; i++)
{
cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
{
cookieValue = cookie.getValue();
}
}
}
return cookieValue;
}
}
19
Code that uses the CookieUtil
class to get the value of a cookie
String emailAddress =
CookieUtil.getCookieValue(cookies, "emailCookie");
**To make it easier to get the value of a cookie, you can create a utility class
that contains a method that accepts an array of Cookie object and the name
of the cookie, and then returns the value of the cookie.
20
How to disable cookies in Google Chrome browser?
21
Advantages and Disadvantages
Cookies
Advantages of using cookies
• Cookies are simple to use and implement.
• Occupies less memory, do not require any server resources and are stored on the
user's computer.
Cookies
• We can configure cookies to expire when the browser session ends (session
cookies) or they can exist for a specified length of time on the client’s computer
(persistent cookies).
• Cookies persist a much longer period of time than session state.
• A hidden field is used to store client state. In this case, user information is stored in
hidden field value and retrieved from another servlet.
• The server embeds new hidden fields in every dynamically generated form page for
Hidden Field
the client.
• When the client submits the form to the server, the hidden fields identify the client.
• Web server can send a hidden HTML form field along with a unique session ID as
follows:
23
Example of Hidden Form Field
A Form tag that uses a hidden text field
<form action="cart" method="post">
<input type="submit" value="Add To Cart">
<input type="hidden" name="productCode" value="8601">
Hidden Field
</form>
24
More Example of Hidden Form Field
25
Advantages and Disadvantages
Hidden Form Field
26
URL Rewriting
• URL rewriting is a method of session tracking in which some extra data (session ID)
is appended at the end of each URL.
• This extra data identifies the session. The server can associate this session
URL Rewriting
• This method is used with browsers that do not support cookies or where the user
has disabled the cookies.
format : url?name1=value1&name2=value2
example : hello?sessionid=12345&user=ali
• A name and a value is separated using an equal (=) sign, a parameter name/value
pair is separated from another parameter using the ampersand(&).
27
Example of URL rewriting
28
More examples of URL Rewriting
29
How to use URL encoding to track
sessions if cookies is disabled?
URL Rewriting
• If the user has disabled per-session cookies, you can use URL encoding to
keep track of the ID for the session. To do that, you must convert any
relevant HTML pages to JSPs, and you must encode all relevant URLs.
• When you encode a URL, the session ID is passed to the browser in the URL.
30
A method to encode a URL
Method Description
encodeURL(String url) Returns a string for the specified URL. If
necessary, this method encodes the
session ID in the URL. If not, it returns
URL Rewriting
31
A URL after it has been encoded
URL Rewriting
32
Advantages and Disadvantages
URL Rewriting
33
HTTP Session - Servlet
• HttpSession object is used to store entire session with a specific client. We can store,
retrieve and remove attribute from HttpSession object.
• Any servlet can have access to HttpSession object throughout the getSession()
HTTP Session
34
HTTP Session - JSP
• By default, JSPs have session tracking enabled and a new HttpSession object is
instantiated for each new client automatically.
• Disabling session tracking requires explicitly turning it off by setting the page
HTTP Session
• The JSP engine exposes the HttpSession object to the JSP programmer through
the implicit session object.
• Since session object is already provided to the JSP programmer, the programmer
can immediately begin storing and retrieving data from the object without any
initialization or getSession().
35
Method for request object
Method Description
getSession()
• Returns the HttpSession object associated with
this request. If the request is not associated with a
HTTP Session
Slide 36
Methods for session object
Method Description
setAttribute(
String name, Object o) Stores any object in the session
HTTP Session
37
How to set and get session attributes?
38
Examples of code that…
Gets a session object
HttpSession session = request.getSession();
Sets a String object as an attribute
session.setAttribute("productCode", productCode);
HTTP Session
39
More methods of the session object
Method Description
getAttributeNames() Returns a java.util.Enumeration object that
contains the names of all attributes in the
HTTP Session
HttpSession object.
getId() Returns a string for the unique Java session
identifier that the servlet engine generates for
each session.
isNew() Returns a true value if the client does not yet
know about the session or if the client chooses
not to join the session.
40
More methods of the session object (cont.)
Method Description
setMaxInactiveInterval
(int seconds)
By default, the maximum inactive interval
HTTP Session
41
Examples of code
A method that gets all the names of the attributes for a session
Enumeration names = session.getAttributeNames();
while(names.hasMoreElements())
HTTP Session
{
System.out.println((String) names.nextElement());
}
A method that gets the ID for a session
String jSessionId = session.getId();
A method that sets the inactive interval for a session
session.setMaxInactiveInterval(60*60*24); // one day
session.setMaxInactiveInterval(-1); // until the browser is closed
A method that invalidates the session and unbinds any objects
session.invalidate();
42
Examples of code
Cart cart;
synchronized(session)
{
cart = (Cart) session.getAttribute("cart");
}
synchronized(session)
{
session.setAttribute("cart", cart);
}
43
A web browser with three windows
accessing the same session object
HTTP Session
44
How to provide thread-safe
access to the session object?
• Each servlet creates one session object that exists for multiple
HTTP Session
45
Advantages and Disadvantages
HTTP Session
• There are no restrictions on the size of the object, any kind of object can be stored in
a session.
• The usage of the session is not dependent on the client’s browser.
• It is secure and transparent.
46
Summary
• HTTP is a stateless protocol, so web application must provide for session tracking.
• Session tracking enable an application to relate each request to a specific browser
and to the data for that session.
• To provide for session tracking, Java creates one session object for each browser.
Summary
Then, you can add attributes like variables and objects to this session object, and
can retrieve the values of these attributes in any of the servlet and JSPs that are run
during the session.
• There are four techniques session tracking – cookies, hidden field, URL rewriting and
HTTP Session.
• In general, it is considered a best practice to implement session tracking by using
cookies. The session ID is stored in a cookie on the user’s browser. However, it
doesn’t work unless the browser enables cookies.
• It’s also possible to implement session tracking by using URL encoding. This work
even when the browser doesn’t enable cookies.
• To pass parameters to a servlet, URL rewriting or hidden fields also can be used.
• HttpSession object is used to store entire session with a specific client.
47
TOPIC 5 – Java Web Session Tracking
The End
Credit:
The content in this slide is based on textbook -
Murach's Java Servlets/JSP (3rd Ed.)
© 2014, Mike Murach & Associates, Inc