Home Jsp JSP Cookies Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JSP Cookies Example

Advertisement
This tutorial shows how to handle cookies in JSP pages. In this tutorial you will learn how to add cookies through jsp page and then show the value of the same cookie in another JSP page.

JSP Cookies Example

        

This tutorial shows how to handle cookies in JSP pages. In this tutorial you will learn how to add cookies through jsp page and then show the value of the same cookie in another JSP page.

Let's understand the cookies. Cookies are short pieces of data sent by web servers to the client browser. The cookies are saved to clients hard disk in the form of small text file. Cookies helps the web servers to identify web users, by this way server tracks the user. Cookies pay very important role in the session tracking.

Cookie Class

In JSP cookie are the object of the class javax.servlet.http.Cookie. This class is used to creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. 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.

The getCookies() method of the request object returns an array of Cookie objects. Cookies can be constructed using the following code:

Cookie(java.lang.String name, java.lang.String value)

Cookie objects 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 Using Cookies

No we will write code in JSP file to set and then display the cookie.

Create Form

Here is the code of the form (cookieform.jsp) which prompts the user to enter his/her name.

<%@ page language="java" %>
<html>
<head>
<title>Cookie 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>

Above form prompts the user to enter the user name. User input are posted to the setcookie.jsp file, which sets the cookie. Here is the code of setcookie.jsp file:

<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
if(username==null) username="";


Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);


%>

<html>
<head>
<title>Cookie Saved</title>
</head>
<body>
<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>

</body>

Above code sets the cookie and then displays a link to view cookie page. Here is the code of display cookie page (showcookievalue.jsp):

<%@ page language="java" %>
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++) 
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
}
}
}

%>
<html>
<head>
<title>Show Saved Cookie</title>
</head>
<body>


<%
if (myCookie == null) {
%>
No Cookie found with the name <%=cookieName%>
<%
} else {
%> 
<p>Welcome: <%=myCookie.getValue()%>.
<%
}
%>
</body>

When user navigates to the above the page, cookie value is displayed.

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 13, 2008

Ask Questions?    Discuss: JSP Cookies Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Gummalla Anand
September 27, 2011
//java complete,html

good but we need more examples about cookies....
ganesh tidke
September 28, 2011
solution to my quetions

what is use of session and coockies and how they implemeneted
T.Siilambarasan
February 20, 2012
Thanks

Thank you for your Guidence!
tabitha
April 2, 2012
cookies

what is the output of it.what we get in out?
ramu
April 8, 2012
JSP

Good Eamples in cookies
Jaqueline
August 25, 2012
lhIKREMDotslUhCai

Hi Andy, I checked you in at the YFC golf ouintg yesterday 8/1 that my husband was running. It wasn't long before the other 2 ladies and I just had to open a package. We tried the triple chip. WOW. Your cookies were (and still are!) the best I have EVER eaten .and I am a home baker! Jack and my family have nearly devoured the two bags we brought home and I can't wait to find them in a store near us. Congratulations on a terriffic product and a big THANK YOU for bringing them to Mill River for the golf ouintg. Becky .for the whole Crabtree family!
dhanush
November 24, 2012
nice

very nice
Tillie Brown
June 13, 2013
Yahoo says I need cookies to open it

I used to be able to open it, I don't know what happened to the cookies. Please help
David
April 21, 2014
Session ID cookie name

Hello. Usually, the session ID Cookie is named JSESSIONID, but that can be overridden. Is there a way to get the name of the session cookie inside jsp? I can get the value with ${pageContext.session.id}, but that is of no use if I don't know the name of the cookie
DMCA.com