Cookies in JSP


 

Cookies in JSP

In this section, we will discuss about handling cookies in JSP with an example.

In this section, we will discuss about handling cookies in JSP with an example.

Cookies in JSP

In this section, we will discuss about handling cookies in JSP with an example. Cookies are small chunk of textual information that a web server sends to a web browser. The cookies are saved to clients hard disk in the form of small text file. Cookies have very important role in the session tracking. By reading information from the cookie which the web server sent it previously, the previously visited sites can offer visitors with a number of conveniences:-

  • Managing user identity during an e-commerce session : In online shopping stores, since the HTTP connection is closed after each page is sent, When the user selects a new item for his cart, how does the store know that he is the same user that put the previous item in his cart? Cookies are a good way of accomplishing this.
  • Remembering username & password :  Many sites requires registration to use their services, When a user registers, a cookie is sent with a unique user ID. When the client reconnects at a later date, the user ID is returned, the server looks it up, determines it belongs to a registered user, and doesn't require an explicit username and password.
  • Customizing user settings at home page :  Many "portal" sites let you customize the look of the main page. They use cookies to remember what you wanted, so that you get that result initially next time.
  • Displaying Ads:  The search engines charge their customers much more for displaying "directed" ads than "random" ads. That is, if you do a search on "Java Servlet", a search site can charge much more for an ad for a servlet development environment than an ad for an on-line travel agent. On the other hand, if the search had been "Bali Hotels", the situation would be reversed. The problem is that they have to show a random ad when you first arrive and haven't yet performed a search, as well as when you search on something that doesn't match any ad categories. Cookies let them remember "Oh, that's the person who was searching for such and such previously" and display an appropriate "high priced" ad instead of a random  "cheap" one.

Browsers generally only accept 20 cookies per site and 300 cookies total, and each cookie is limited to 4KB.

Drawbacks :

  • First, due to privacy, some users turn off cookies. So, even when you use cookies to give added value to a site, your site shouldn't depend on them.
  • Second, as the author of JSP/servlet that use cookies, you should be careful not to trust cookies for particularly sensitive information, since this would open the user up to risks if somebody accessed their computer or cookie files.

Cookie class : In JSP , cookie are the object of the class javax.servlet.http.Cookie .A cookie's value can uniquely identify a client, so cookies are commonly used for session management. 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. A Cookie object may be added to an HttpResponse object using HttpResponse.addCookie(). To extract a cookie from an HttpRequest object, you can use HttpRequest.getCookies() , which returns an array of Cookie objects representing all the cookies included in the request.

Cookies can be constructed using the following code:

 Cookie cookie-name = new Cookie(java.lang.String name, java.lang.String value) ;

Cookie class have the following methods :

Method      Description                           
getComment()       Returns the comment describing the purpose of this cookie,
or null if no such comment has been defined.
getMaxAge() Returns the maximum specified age of the cookie.
getName() Returns the name of the cookie.
getPath() Returns the prefix of all URLs for which this cookie is targeted.
getValue()  Returns the value of the cookie.
setComment(String )  If a web browser presents this cookie to a user, the cookie's
purpose will be described using this comment.
setMaxAge(int) Sets the maximum age of the cookie. The cookie will expire after
that many seconds have passed. Negative values indicate the default
behavior: the cookie is not stored persistently, and will be deleted
when the user web browser exits. A zero value causes the cookie
to be deleted
setPath(String) This cookie should be presented only with requests beginning with
 this URL.
setValue(String) Sets the value of the cookie. Values with various special characters
(white space, brackets and parentheses, the equals sign, comma,
double quote, slashes, question marks, the "at" sign, colon, and
semicolon) should be avoided. Empty values may not behave the
same way on all browsers.

Example :

In this example , we will set the cookie & then display it in a JSP page.

Below the code of the form which prompts the user to enter his/her name :

cookieform.jsp

<html>

<head>

<title>Input Form</title>

</head>

<body>

<form method="post" action="setcookie.jsp">

<p><b>Enter Your Name: </b><input type="text" name="username"><br>

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

</form>

</body>

</html>

Given below the code for setting value of cookie :

setcookie.jsp

<%@ page language="java" import="java.util.*"%>

<%

String username=request.getParameter("username");

if(username==null) username="";

Date now = new Date();

Cookie cookie = new Cookie ("username",username);

cookie.setMaxAge(365 * 24 * 60 * 60);

0

response.addCookie(cookie);

%>

<html>

1

<head>

<title>Saving Cookie</title>

</head>

2

<body>

<p><a href="showcookievalue.jsp">click here to see Next Page to view the cookie value</a></p>

</body>

3

Given below the code for showing the value of the cookie ,which is user's entered name :

showcookievalue.jsp

<%@ page language="java" %>

4

<%

String cookieName = "username";

Cookie cookies [ ] = request.getCookies ();

5

Cookie myCookie = null;

if (cookies != null)

{

6

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

{

if (cookies [i].getName().equals (cookieName))

7

{

myCookie = cookies[i];

break;

8

}

}

}

9

%>

<html>

<head>

0

<title>Show Saved Cookie</title>

</head>

<body>

1

 

<%

2

if (myCookie == null) {

%>

No Cookie found with the name <%=cookieName%>

3

<%

} else {

%>

4

<h3><font color="red">Welcome: <%=myCookie.getValue()%></font></h3>

<%

}

5

%>

</body>

</html>

6

OUTPUT :

After submitting name, final output(value of the cookie) displays as :

7

Download Source Code

Ads