• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cookie and jsp

 
Cynthia Yao
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I try to test cookie settings in jsp. Something strange result. Here is the code
<%out.println("start");
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);
SessionCookie.setMaxAge(600*600);
response.addCookie(SessionCookie);
%>
<html><head><title>Test Cookies</title></head>
<body>
<%
} else if (cookies!=null) {
out.println("Cookie exists");
out.println(cookies[0].getValue());
out.println(cookies[0].getMaxAge());
}
%></body></html>
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
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Bill

------------------
author of:
 
Cynthia Yao
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic