The JSP Files (part 6): State Of Grace - ...And Read
(Page 5 of 9 )
So that takes care of writing a cookie - but how about reading it? Here'sthe code.
<%
// declare some variables
Cookie cookieCounter = null;
// the cookie you want
String cookieName = "counter";
int cookieFound = 0;
// a few more useful variables
String tempString;
int count=0;
// get an array of all cookies available on client
Cookie[] cookies = request.getCookies();
// iterate through array looking for your cookie
for(int i=0; i<cookies.length; i++)
{
cookieCounter = cookies[i];
if (cookieName.equals(cookieCounter.getName()))
{
cookieFound = 1;
break;
}
}
%>
Before you can read the cookie, you need to find it on the client's harddrive. Since JSP does not currently allow you to directly locate andidentify the cookie by name, you need to iterate through all availablecookies until you find the one you're looking for. In the example above,the "for" loop does just that; if and when it finds the cookie, it sets the"cookieFound" variable to 1 and breaks out of the loop.
At this point, the cookie is stored in the Cookie object "cookieCounter".You can then use the getValue() object method to get the current value ofthe cookie variable, and use it in your script.
<%
// if found
if(cookieFound == 1)
{
// get the counter value as string
tempString = cookieCounter.getValue();
// convert it to a number
count = Integer.parseInt(tempString);
// increment it
count++;
// back to a string
tempString = Integer.toString(count);
// store it in the cookie for future use
cookieCounter.setValue(tempString);
// set some other attributes
cookieCounter.setMaxAge(300);
cookieCounter.setPath("/");
// send cookie to client
response.addCookie(cookieCounter);
}
%>
Next: What's In A Name? >>
More Java Articles
More By Vikram Vaswani and Harish Kamath, (c) Melonfire