wood burning stoves
The moose likes Servlets and the fly likes cookie and jsp Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "cookie and jsp" Watch "cookie and jsp" New topic

cookie and jsp

Cynthia Yao
Ranch Hand

Joined: Nov 06, 2000
Posts: 92

I try to test cookie settings in jsp. Something strange result. Here is the code
Cookie cookies[]=request.getCookies();
String sessionid=session.getId();
Cookie SessionCookie=null;
if (cookies==null) {
out.println("<br>Session Cookie added<br>");
SessionCookie = new Cookie("SessionID", sessionid);
<html><head><title>Test Cookies</title></head>
} else if (cookies!=null) {
out.println("Cookie exists");
The first time I run it, I got a "array out of bound" error. I refresh it, the cookies information will show. However, the max age is showing as -1. I am not sure whether this cookie is set by the page or not. Also, I can not found the cookie text file on my hard drive.
Thank in advance
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13035
The reason you got that error is that the array can exist but still be empty - try
else if (cookies!=null && cookies.length > 0 ) {
The first time you visit the page, there may be no cookies.
The default age of -1 means the cookie only lasts until the browser is shut down - you need to make the cookie persistent before it will be stored on disk.

author of:
Cynthia Yao
Ranch Hand

Joined: Nov 06, 2000
Posts: 92
Thanks William.
What you said stop the error message.
However, the displayed cookie is not actually set by me, but rather by either the HttpSession or request because when I comment out my create cookie and add cookie part, the cookie information still displays. I wonder whether it is because I use jsp not servlet. Somehow I can not change the cookie maxtime. Has anyone have similiar experience?
I agree. Here's the link: http://aspose.com/file-tools
subject: cookie and jsp
It's not a secret anymore!