View RSS Feed

My Java Tips

Handling Cookies in JSP

Rate this Entry
by , 11-20-2011 at 06:04 PM (2921 Views)
Cookies are text files that are downloaded onto a visitor's hard drive to store the visitor's actions in order to better
customize their following visits. We may handle cookies in JSP and I will show you how to do that.

JSP provides an implicit response object which is used to add cookies. To add a cookie to the response, addCookie method is used.
We may store useful information in cookies for later use and this method is perfect for our needs.
Java Code:
response.addCookie(Cookie exforsys);
Now I will present a meaningful example to how to set and retrieve cookies. The following form is used to take username form the user. When submitted, it posts the username to setcookies.jsp, which is responsible for storing the information into cookie.

Java Code:
<%@ page language="java" %>

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

<strong>Enter Your Name: </strong>
<input name="username" type="text" /> 
<input value="Submit" type="submit" />

I will continue the example.
The page below gets the posted values using request object and stores it into a cookie. It then displays a link to showcookievalue.jsp, which shows the value stored in the cookie.

Java Code:
&lt;%@ page language="java" import="java.util.*"%&gt;
&lt;% 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); %&gt;

<a href="showcookievalue.jsp">Next Page to view the cookie value</a>
The code presented is simple. We simply get the username from the posted form, and store the value in a cookie. Creating the cookie and setting its age is important here.

Presented below is a page that reads contents for the cookies and displays it to the user.

Java Code:
&lt;%@ page language="java" %&gt;
&lt;% String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
for (int i = 0; i &lt; cookies.length; i++)
if (cookies [i].getName().equals (cookieName))
myCookie = cookies[i];
} } }

&lt;% if (myCookie == null)
No Cookie found with the name &lt;%=cookieName%&gt;
&lt;% } else { %&gt;

Welcome: &lt;%=myCookie.getValue()%&gt;.
&lt;% } %&gt;
We created an array of cookies, since there can be more than one cookie stored. Then we read all the cookies into that array. Note that you may only retrieve cookies stored by your site (domain). Then we simply retrieved the stored value from the cookie with name "username".

Try it. Happy coding.

Submit "Handling Cookies in JSP" to Facebook Submit "Handling Cookies in JSP" to Digg Submit "Handling Cookies in JSP" to Submit "Handling Cookies in JSP" to StumbleUpon Submit "Handling Cookies in JSP" to Google

Java EE , JSP