T.Y.B.Sc.(I.T.
) - Sem V Cookies Enterprise Java
Unit - II
Chapter 2 : COOKIES
Notes Prepared By: Asst. Prof. Pranali Patil
1
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Notes Prepared By: Asst. Prof. Pranali Patil
2
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Notes Prepared By: Asst. Prof. Pranali Patil
3
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
How Cookie works?
By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user
as the old user.
Cookies are often used for Session management or in situations where it is required uniquely
identify a client.
The Cookie class allows Servlets to:
● Read, create and manipulate HTTP-style cookies
● Store small amounts of data on the client
A servlet uses getCookies() of HttpServletRequest to retrieve cookies submitted as part of client
request.
addCookie() of HttpServletResponse() can be used to send a new cookie to the Web browser.
Where Cookies are used?
In the real world, cookies are useful:
● To create a temporary session where the site in some way remembers in the short term what
the user was doing or had chosen between web page requests, for example remembering:
Who the user is logged in as at the moment
What the user has ordered from an online shopping cart
● To remember low-security information more permanently, for example, to remember:
A user’s search results preferences
What topic had the user browsed on the user’s last visit
● To compile user statistics, for example, for advertising purpose or for improvising the
functionality of a site.
Notes Prepared By: Asst. Prof. Pranali Patil
4
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
● To identify a user during an E-commerce session
● To avoid keying in username and password to login to the site
Notes Prepared By: Asst. Prof. Pranali Patil
5
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Constructor of Cookie class:
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String constructs a cookie with a specified name and
value) value.
Following are the methods available in this class:
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be changed after
creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
Notes Prepared By: Asst. Prof. Pranali Patil
6
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Cookie Expiration
One important- Cookie setting is the cookie expiration time. This time tells the browser
receiving the cookie how long time it should keep the cookie before deleting it. You set the
cookie expiration time via the setMaxAge() method. This method takes the number of seconds
the cookie is to live as a parameter. Here is an example:
Cookie cookie = new Cookie("uid", "123");
cookie.setMaxAge(24*60* 60); // 24 hours.
response.addCookie(cookie);
This example first creates a Cookie instance with the name "uid" and the value "123". Second, it
sets the expiration to 24 hours using the setMaxAge() method. 24 hours is 60 seconds x 60
minutes x 24 hours (24 x 60 x 60). Finally the example sets the cookie on the
HttpServletResponse object, so the cookie is included in the response sent to the browser.
Notes Prepared By: Asst. Prof. Pranali Patil
7
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Removing Cookies
Sometimes you may want to remove a cookie from the browser. You do so by setting the cookie
expiration time. You can set the expiration time to 0 or -1. If you set the expiration time to 0 the
cookie will be removed immediately from the browser. If you set the expiration time to -1 the
cookie will be deleted when the browser shuts down.
Here is an example:
Cookie cookie = new Cookie("uid", "");
cookie.setMaxAge(0);
response.addCookie(cookie);
If the browser already has a cookie stored with the name "uid", it will be deleted after receiving
the cookie with the same name ("uid") with an expiration time of 0. If the browser did not
already have the cookie stored, this new cookie is just thrown out immediately since its
expiration time is 0.
Example:
Q.1 Create a servlet that uses Cookies to store the number of times a user has visited a
servlet.
Solution:
CookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServlet extends HttpServlet
{
private int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String k=String.valueOf(i);
Notes Prepared By: Asst. Prof. Pranali Patil
8
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("This is the first time you are visiting this page");
}
else
{
synchronized(CookieServlet.this)
{
out.println("You visited this page "+i+" times");
}
}
i++;
}
}
Notes Prepared By: Asst. Prof. Pranali Patil
9
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Q. 2 Write a servlet that accepts a username from an html form and stores it as a cookie
variable. Write another servlet that returns the value of this cookie variable and displays
it.
Coding:
CookiesHtml.html
<html>
<form action="AddCookieServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</html>
AddCookieServlet.java
import java.io.*;
Notes Prepared By: Asst. Prof. Pranali Patil
10
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response){
try
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n); //creating cookie object
response.addCookie(ck); //adding cookie in the response
//creating submit button
out.print("<form action='GetCookie'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
Notes Prepared By: Asst. Prof. Pranali Patil
11
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
GetCookie.java
import java.io.*;
import javax.servlet.http.*;
public class GetCookie extends HttpServlet
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response){
try
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
Notes Prepared By: Asst. Prof. Pranali Patil
12
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Output:-
Notes Prepared By: Asst. Prof. Pranali Patil
13
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Advantages of persistent cookies
● Persistent cookies can be used to store information that needs to be accessed across
multiple browsing sessions, such as login credentials and language preferences.
● Persistent cookies can be used to track a user's behavior on a website over time, which
can be used to personalize the user's experience.
● Persistent cookies can be used to remember a user's preferences, such as their
preferred layout or font size.
Disadvantages of persistent cookies
● Persistent cookies take up space on the user's device, which can slow down their
browsing experience.
● Persistent cookies can be used to track a user's behavior across multiple websites,
which can be seen as a privacy concern.
● Persistent cookies can be used to store sensitive information, such as login credentials,
which can be a security risk if the cookie is accessed by an unauthorized party.
Examples of when to use persistent cookies
● Login credentials: Persistent cookies can be used to store a user's login credentials so
that they do not have to log in every time they visit a website.
● Language preferences: Persistent cookies can be used to remember a user's
language preference so that the website is displayed in the correct language.
● Personalized advertising: Persistent cookies can be used to track a user's behavior
on a website and across multiple websites to deliver personalized advertising.
Notes Prepared By: Asst. Prof. Pranali Patil
14
T.Y.B.Sc.(I.T.) - Sem V Cookies Enterprise Java
Advantages of session cookies
● Session cookies are temporary and are automatically deleted when a user closes their
browser. This means that they do not take up any space on the user's device.
● Session cookies can be used to keep a user's information secure because they only last
for the duration of a single browsing session.
● Session cookies are easy to implement and do not require any special configuration.
Disadvantages of session cookies
● Session cookies cannot be used to store information that needs to be accessed across
multiple browsing sessions.
● If a user closes their browser or their session expires, any information stored in a
session cookie will be lost.
Examples of when to use session cookies
● Shopping cart functionality: Session cookies can be used to store the items that a
user has added to their shopping cart during a single browsing session.
● Login credentials: Session cookies can be used to store a user's login credentials
during a single browsing session. This allows the user to navigate the website without
having to log in again for each page they visit.
● Form data: Session cookies can be used to store data that a user enters into a form on
a website, such as a search form or a contact form. This data can be used to
pre-populate the form if the user navigates away from the page and then returns to it
later.
Notes Prepared By: Asst. Prof. Pranali Patil
15