Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials:
 

Software Solutions and Services
 

 
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
 
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.

 

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.

 

                          

» View all related tutorials
Related Tags: c io sed page tag if for example to exam ci e use in m ad age xa xamp s

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

18 comments so far (
post your own) View All Comments Latest 10 Comments:

i just use the cookie example,i use 3 ie to run a single program with various input..
While use of cookie ,the page should show the various outputs...
but it shows the value which is submit last in all 3 pages....
so the example cookie not give correct answer...

Posted by edwin on Friday, 12.5.08 @ 23:41pm | #82459

i just learn the basic, and the examples are very useful to understand easily....

Posted by edwin on Friday, 12.5.08 @ 23:01pm | #82456

Very nice explanation...

Posted by Dhruvi on Tuesday, 09.9.08 @ 18:46pm | #78312

This is very good site.This site very useful to me.
Giving very good example with synataxes

Posted by srinu on Friday, 08.8.08 @ 12:49pm | #71765

This is very simple and good understandable example.

Posted by Manohar on Thursday, 06.12.08 @ 11:17am | #63092

it is really an interesting and easy way of learning JSP..but one thing i would like to say here.how we can view the more the one values stored inside the cookie.while displaying the third page....please upload more and more samples on Advance JSP..Thanks Alot..........

Posted by ISMAIL on Wednesday, 04.30.08 @ 15:45pm | #58215

There is one flaw.Dont enter any value in the first page.Press submit than press on the link.

It is showing "welcome:."
It should show error message.

Posted by Krunal on Sunday, 03.30.08 @ 00:14am | #54684

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); %>

Posted by Parameter on Wednesday, 03.12.08 @ 22:53pm | #52502


it was really nice . thank u ! but one thing

i would like to say here first of all enter user name after that it will show the next link page and then again clicking that link it will show the saved cookie . but whenever again whenever i entered a new cookie it won't displaying the old cookie , it simply showing the new cookie . i got confused so please help me.

Posted by dasari on Friday, 02.15.08 @ 12:42pm | #48371

Thanks for tutorial. It is easy for understanding.

Posted by Phong Tran on Wednesday, 02.13.08 @ 11:54am | #48125

Training Courses
Tell A Friend
Your Friend Name
Website Designing Services
 
Web Designing Packages From $150!
 
Website Designing Company Web Hosting
 
Website Designing Quotation
 
Search Tutorials:

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.