0% found this document useful (0 votes)
20 views14 pages

Lab 9 Create and Read Cookies Using Javascript ASP JSP

Uploaded by

Adarsh Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views14 pages

Lab 9 Create and Read Cookies Using Javascript ASP JSP

Uploaded by

Adarsh Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

IWT LAB: MCA 214 Dr.

Gitanjali Nikam

Experiment No. 9

Problem: Implement program to create and read cookies using JavaScript /ASP
/JSP.

Cookies

A cookie is a piece of data that is stored on your computer to be accessed by your browser.
You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you
ever saved your Facebook password so that you do not have to type it each and every time
you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.

Need of Cookie

The communication between a web browser and server happens using a stateless protocol
named HTTP. Stateless protocol treats each request independent. So, the server does not
keep the data after sending it to the browser. But in many situations, the data will be
required again. Here come cookies into a picture. With cookies, the web browser will not
have to communicate with the server each time the data is required. Instead, it can be
fetched directly from the computer.

o When a user sends a request to the server, then each of that request is treated as a new request
sent by the different user.
o So, to recognize the old user, we need to add the cookie with the response from the server.
o browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with that request
automatically. Due to the cookie, the server recognizes the users.

1
IWT LAB: MCA 214 Dr. Gitanjali Nikam

Javascript Set Cookie

You can create cookies using document.cookie property like this.

document.cookie = "cookiename=cookievalue"

You can even add expiry date to your cookie so that the particular cookie will be removed
from the computer on the specified date. The expiry date should be set in the UTC/GMT
format. If you do not set the expiry date, the cookie will be removed when the user closes
the browser.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC"

You can also set the domain and path to specify to which domain and to which directories
in the specific domain the cookie belongs to. By default, a cookie belongs to the page that
sets the cookie.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC; path=/ "

//create a cookie with a domain to the current page and path to the entire domain.

JavaScript get Cookie

You can access the cookie like this which will return all the cookies saved for the current
domain.

2
IWT LAB: MCA 214 Dr. Gitanjali Nikam

var x = document.cookie

JavaScript Delete Cookie

To delete a cookie, you just need to set the value of the cookie to empty and set the value
of expires to a passed date.

document.cookie = "cookiename= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"

Example:

<html>

<head>

<title>Cookie!!!</title>

<script type="text/javascript">

function createCookie(cookieName,cookieValue,daysToExpire)

var date = new Date();

date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));

document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();

function accessCookie(cookieName)

var name = cookieName + "=";

var allCookieArray = document.cookie.split(';');

for(var i=0; i<allCookieArray.length; i++)

var temp = allCookieArray[i].trim();


3
IWT LAB: MCA 214 Dr. Gitanjali Nikam

if (temp.indexOf(name)==0)

return temp.substring(name.length,temp.length);

return "";

function checkCookie()

var user = accessCookie("testCookie");

if (user!="")

alert("Welcome Back " + user + "!!!");

else

user = prompt("Please enter your name");

num = prompt("How many days you want to store your name on your computer?");

if (user!="" && user!=null)

createCookie("testCookie", user, num);

</script>

</head>

<body onload="checkCookie()"></body>

</html>

4
IWT LAB: MCA 214 Dr. Gitanjali Nikam

Using JSP:
Cookies are the text files which are stored on the client machine. They are used to track the information
for various purposes. It supports HTTP cookies using servlet technology The cookies are set in the
HTTP Header. If the browser is configured to store cookies, it will keep information until expiry date.

Following are the cookies methods:

Public void setDomain(String domain)

It is used to set the domain to which the cookie applies

Public String getDomain()

It is used to get the domain to which cookie applies

Public void setMaxAge(int expiry)

It sets the maximum time which should apply till the cookie expires

Public intgetMaxAge()

It returns the maximum age of cookie

Public String getName()

It returns the name of the cookie

Public void setValue(String value)

Sets the value associated with the cookie

Public String getValue()

Get the value associated with the cookie

Public void setPath(String path)

It sets the path to which cookie applies

Public String getPath()

It gets the path to which the cookie applies

Public void setSecure(Boolean flag)

5
IWT LAB: MCA 214 Dr. Gitanjali Nikam

It should be sent over encrypted connections or not.

Public void setComment(String cmt)

It describes the cookie purpose

Public String getComment()

It the returns the cookie comments which has been described.

How to Handle Cookies in JSP

1. Creating the cookie object


2. Setting the maximum age
3. Sending the cookie in HTTP response headers

Example:

In this example, we are creating cookies of username and email and add age to the cookie for 10
hours and trying to get the variable names in the action_cookie.jsp

Action_cookie.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Guru Cookie</title>

</head>

6
IWT LAB: MCA 214 Dr. Gitanjali Nikam

<body>

<form action="action_cookie_main.jsp" method="GET">

Username: <input type="text" name="username">

<br />

Email: <input type="text" name="email" />

<input type="submit" value="Submit" />

</form>

</body>

</html>

Action_cookie_main.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<%

Cookie username = new Cookie("username",

request.getParameter("username"));

Cookie email = new Cookie("email",

request.getParameter("email"));

username.setMaxAge(60*60*10);

email.setMaxAge(60*60*10);

// Add both the cookies in the response header.

7
IWT LAB: MCA 214 Dr. Gitanjali Nikam

response.addCookie( username );

response.addCookie( email );

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Guru Cookie JSP</title>

</head>

<body>

<b>Username:</b>

<%= request.getParameter("username")%>

<b>Email:</b>

<%= request.getParameter("email")%>

</body>

</html>

Explanation:

Action_cookie.jsp

Here we are taking a form which has to be processed in action_cookie_main.jsp. Also, we are taking
two fields "username" and "email" which has to be taken input from the user with a submit button.

8
IWT LAB: MCA 214 Dr. Gitanjali Nikam

Action_cookie_main.jsp

Creating two cookie objects of "username" and "email" using request.getParameter.

Here we are adding age to both the cookies, which have been created of 10 hours i.e. cookies will
expire in that age.

Adding cookies to the session of username and email and these two cookies can fetched when
requested by getParameter().

Output:
When you execute the above code you get the following output:

Using ASP:
ASP.Net Cookie Example

Cookies is a small pieces of text information which is stored on user hard drive using users browser for
identify users. It may contain username, ID, password or any information. Cookie does not use server
memory.

Cookies stored user computer at “C”\Document and Setting\Current login_User\Cookie”.

9
IWT LAB: MCA 214 Dr. Gitanjali Nikam

Types of Cookies
1. Persistence Cookie
2. Non-Persistence Cookie

1. Persistence Cookie

These types of cookies are permanently stored on user hard drive. Cookies which have an expiry date
time are called persistence cookies. This type of cookies stored user hard drive permanently till the date
time we set.

Example to create persistence cookie

Response.Cookies[“name”].Value = “Meera Academy”;


Response.Cookies[“MeeraAcademy”].Expires = DateTime.Now.AddMinutes(10);

we can also create same cookies as like below

HttpCookie strname = new HttpCookie(“name”);


strname.Value = “Meera Academy”;
strname.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(strname);

In above code we use Response.Cookies object for create Cookie.


In above example we have set 10 Minute time for Expire Cookie, we can retrieve cookie values up to 10
minutes, after 10 minutes the cookies automatically expires.

2. Non-Persistence Cookie

These types of cookies are not permanently stored on user hard drive. It stores the information up the user
accesng the same browser. When user close the browser the cookies will be automatically deleted.

Example to create non-persistnce cookie

Response.Cookies[“name”].Value = “Meera Academy”;

we can also create same non-persistence cookies as

10
IWT LAB: MCA 214 Dr. Gitanjali Nikam

HttpCookie strname = new HttpCookie(“name”);


strname.Value = “Meera Academy”;
Response.Cookies.Add(strname);

Read Cookie Information

if (Request.Cookies[“name”] != null)
{
Label1.Text = Request.Cookies[“name”].Value;
}

ASP.Net Cookie Example


Open visual studio and design web form as shows below figure for create cookie and retrieve cookie
information.

Cookie Example in ASP.Net


C# code for Cookie Example

Create Cookie Button C# Code

protected void btncreate_Click(object sender, EventArgs e)


{
Response.Cookies["name"].Value = txtcreatecookie.Text;
Response.Cookies["name"].Expires = DateTime.Now.AddMinutes(1);

11
IWT LAB: MCA 214 Dr. Gitanjali Nikam

Label1.Text = "Cookie Created";


txtcreatecookie.Text = "";
}

Here, we create cookie with name parameter and assign textbox values to name cookie and also set expiry
time 1 minute. The cookie destroyed after 1 minute.

Retrieve Cookie Button Code

protected void btnretrieve_Click(object sender, EventArgs e)


{
if (Request.Cookies["name"] == null)
{
txtretrieve.Text = "No cookie found";
}
else
{
txtretrieve.Text = Request.Cookies["name"].Value;
}
}

On retrieve cookie button checks if cookie value not null then display cookie value in result, but after 1
minute the cookie expires, after 1 minute cookie value will be null and result will be “No cookie found”.

Questions:
What are cookies?
Who can access?
Explain the types of internet Cookies.
What are HTTP cookies?

1. Cookies were originally designed for ____________


a) Client side programming
b) Server side programming
c) Both Client side programming and Server side programming
d) Socket programming

Answer: b

12
IWT LAB: MCA 214 Dr. Gitanjali Nikam

2. The Cookie manipulation is done using which property?


a) cookie
b) cookies
c) manipulate
d) manipulate cookie

Answer: a

3. Which of the following explains Cookies nature?


a) Non Volatile
b) Volatile
c) Intransient
d) Transient

Answer: d

4. Which attribute is used to extend the lifetime of a cookie?


a) Higher-age
b) Increase-age
c) Max-age
d) Lifetime

Answer: c

5. Which of the following defines the Cookie visibility?


a) Document Path
b) LocalStorage
c) SessionStorage
d) All of the mentioned

Answer: d

13
IWT LAB: MCA 214 Dr. Gitanjali Nikam

14

You might also like