0% found this document useful (0 votes)
46 views

IP Topic5 Session Tracking

Uploaded by

Abdullahi Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

IP Topic5 Session Tracking

Uploaded by

Abdullahi Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

SECJ 3303 –

INTERNET PROGRAMMING

TOPIC 5 –
JAVA WEB SESSION TRACKING

UTM JOHOR BAHRU


OBJECTIVES
Applied
• Provide for session tracking by using cookies, HTTP session and URL encoding.
• Provide for parameter passing by using URL rewriting and hidden fields.
• Test your web applications with cookies enabled and with cookies disabled.
• Write a utility class that includes a static method for getting a specific cookie from
a user’s browser.

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

• Session is a particular interval of time.

• Session Tracking is a mechanism used by the Web container to store session


information for a particular user.

• It is also known as a Session Management which is a way to maintain state (data) of


the user.

• 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.

• There are two types of cookies:


• persistent cookies are store on the user’s PC. It is valid for multiple session . It is
not removed each time when user closes the browser. It is removed only if user
logout or sign-out.
• per-session cookies (non-persistent) are deleted when the session ends. It is valid
for single session only. It is removed each time when user closes the browser.

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

server every time it accesses a page from that server.


• Cookies can be set to persist within the user’s browser for up to 3 years.
• Some users disable cookies in their browsers. As a result, you can’t
always count on all users having their cookies enabled.
• Browsers generally accept only 20 cookies from each site and 300
cookies total. In addition, they can limit each cookie to 4 kilobytes.
• A cookie can be associated with one or more subdomain names.

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

scores, and stock quotations.


• To focus advertising like banner ads that target the user’s interests.

11
Cookies
Constructor of the Cookie class

Constructor Description
Cookie(String name, String value) Creates a cookie with the
specified name and value.
Cookies

A method of the response object


Method Description
addCookie(Cookie c) Adds the specified cookie to the response.

A method of the request object

getCookies() Returns an array of Cookie objects that the client sent


with this request. If no cookies were sent, this method
returns a null value.
12
The methods of the Cookie class

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

to –1. Then, the cookie will be deleted


when the user exits the browser.
To allow the entire application to
setPath(String path)
access the cookie, set the cookie’s path
to “/”.
Returns a string for the name of the
getName()
cookie.
Returns a string that contains the value
getValue()
of the cookie.

13
Code that creates and sets a cookie

Cookie userIdCookie = new Cookie("userIdCookie", userId);


userIdCookie.setMaxAge(60*60*24*365*2); //set the age to 2 years
userIdCookie.setPath("/"); // allow access by the entire application
response.addCookie(userIdCookie);
Cookies

Code that gets the cookie


Cookie[] cookies = request.getCookies();
String cookieName = "userIdCookie";
String cookieValue = "";

for (int i=0; i<cookies.length; i++)


{
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
cookieValue = cookie.getValue();
}

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

Cookie[] cookies = request.getCookies();


for (int i=0; i<cookies.length; i++)
{
Cookies

Cookie cookie = cookies[i];


cookie.setMaxAge(0); //delete the cookie
cookie.setPath("/");
//allow the entire application to access it
response.addCookie(cookie);
}

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

Cookie[] cookies = request.getCookies();


Cookies

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?

1. On your computer, open Chrome.


2. At the top right, click More
Settings.
3. Under "Privacy and security,"
Cookies

click Site settings.


4. Then select - Cookies and other
site data.
5. Select Block all cookies.

Your browser will no longer store


cookies.

More info on how to disable cookies in other web browsers:


https://www.avg.com/en/signal/disable-cookies

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.

Disadvantages of using cookies


• User has the option of disabling cookies on his computer from browser’s setting.
• Cookies will not work if the security level is set to high in the browser.
• Users can delete a cookies.
• User’s browser can refuse cookies, so your code has to anticipate that possibility.
• Complex type of data is not allowed (e.g. dataset etc). It allows only plain text
(cookie allows only string content).
22
Hidden Form Field

• 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:

<input type = "hidden" name = "sessionid" value = "12345">

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>

The form displayed in a browser

The URL that displays when the button is clicked

24
More Example of Hidden Form Field

A Form tag that uses JSP expressions to


set hidden field values
Hidden Field

<form action="cart" method="post">


<input type="hidden" name="productCode"
value="<%=product.getCode()%>">
<input type=text size=2 name="quantity"
value="<%=lineItem.getQuantity()%>">
<input type="submit" name="updateButton" value="Update">
</form>

25
Advantages and Disadvantages
Hidden Form Field

Advantages of using hidden form field


Hidden Field

• It will always work whether cookie is disabled or not.


• Hidden boxes reside in web pages of the browser windows, so they do not
provide a burden to the server.

Disadvantages of using hidden form field


• It is maintained at server side.
• Extra form submission is required on each pages.
• Only textual information can be used.
• The hidden box values of the form page can be viewed using the source code
of the web page. That means there is no security and are not appropriate for
secure data like passwords.

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

identifier with the data it has stored about that session.

• This method is used with browsers that do not support cookies or where the user
has disabled the cookies.

• In URL rewriting, a token(parameter) is added at the end of the URL as follow:

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

• An A tag that adds a product code to a URL


<a href="cart?productCode=8601">Add to cart</a>

• The link displayed in a browser


URL Rewriting

• The URL that displays when you click on the link

28
More examples of URL Rewriting

A Form tag that calls a JSP


<form action="cart.jsp?productCode=jr01" method="post">
URL Rewriting

An A tag that uses a JSP expression for the product code


<a href="cart?productCode=<%= productCode %>" >
Add to cart</a>

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

the URL unchanged.

How to encode a URL in a Form tag


<form action="<%=response.encodeURL("cart")%>"
method="post">
How to encode a URL in an A tag
<a href="<%=response.encodeURL("cart?productCode=8601")%>">
Add To Cart
</a>

31
A URL after it has been encoded
URL Rewriting

32
Advantages and Disadvantages
URL Rewriting

Advantages of using URL Rewriting


URL Rewriting

• It will always work whether cookie is disabled or not.


• Extra form submission is not required on each pages.

Disadvantages of using URL Rewriting


• It will work only with links.
• It can send only textual information.
• Most browsers limit the number of characters that can be passed by a URL
to 2,000 characters.
• It’s difficult to include spaces and special characters such as the ? and &
characters in parameter values.
• Every time we need to rewrite the URL with session-id value in the generated
form, for this we must execute the encoded URL() method.

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

method of the HttpServletRequest object.

• The HttpServletRequest interface provides two methods to get the object of


HttpSession:

➢ public HttpSession getSession():Returns the current session associated


with this request, or if the request does not have a session, creates one.

➢ public HttpSession getSession(boolean create):Returns the current


HttpSession associated with this request or, if there is no current session and
create is true, returns a new 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

directive session attribute to false as follows:

<%@ page session = "false" %>

• 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

session, this method creates a new HttpSession


object and returns it.

Slide 36
Methods for session object
Method Description
setAttribute(
String name, Object o) Stores any object in the session
HTTP Session

as an attribute and specifies a


name for the attribute.
getAttribute(String name) Returns the value of the specified
attribute as an Object type. If no
attribute exists for the specified
name, this method returns a null
value.
removeAttribute(String name) Removes the specified attribute
from this session.

37
How to set and get session attributes?

• A session object is created when a browser makes the first request


to a site. It is destroyed when the session ends.
HTTP Session

• A session ends when a specified amount of time elapses without


another request or when the user exits the browser.
• The session object is a built-in JSP object. As a result, you don’t
need to create the session object when working with JSPs.

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

Sets a user-defined object as an attribute


Cart cart = new Cart(productCode);
session.setAttribute("cart", cart);
Gets a String object
String productCode =
(String) session.getAttribute("productCode");
Gets a user-defined object
Cart cart = (Cart) session.getAttribute("cart"); if
(cart == null)
cart = new Cart();
Removes an object
session.removeAttribute("productCode");

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

for the session is set to 1800 seconds (30


minutes). To increase or decrease this
interval, supply a positive integer value.
To create a session that won’t end until
the user closes the browser, supply a
negative integer such as –1.
Invalidates the session and unbinds any
invalidate() objects that are bound to it.

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

An example that synchronizes access to the session object


HTTP Session

Cart cart;
synchronized(session)
{
cart = (Cart) session.getAttribute("cart");
}

Another example that synchronizes access to the session object

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

requests that come from a single client.


• If the client has one browser window open, access to the session
object is thread-safe.
• If the client has multiple browser windows open, it’s possible (though
highly unlikely) that two threads from the same client will access the
session object at the same time.
• As a result, the session object isn’t completely thread-safe.

45
Advantages and Disadvantages
HTTP Session

Advantages of using HTTP Session


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.

Disadvantages of using HTTP Session


• Performance overhead in case of large volumes of data/user, because session data
is stored in server memory.

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

UTM JOHOR BAHRU

You might also like