Another question about cookies (this is my first time using them and I'm struggling a bit). My code (and output from the logs) is below. The code is part of a voting system, and we only want someone to vote once a day- so we check if they already have the cookie, and if not, set the cookie and process the vote. It seems that my cookie is never being set- no matter how many times I run the
servlet, it only retrieves 1 cookie, and enters into the block to set the cookie (evidenced by the output in the logs)- and I can't find the cookie on my hard drive. Anyway, I am completely stumped and would welcome any input.
--------------
Source Code:
(in doPost method):
Cookie [] cookies = null;
cookies = request.getCookies();
if (cookies != null)
{
System.out.println("Length of cookie array= " + cookies.length);
for (int i=0; i< cookies.length; i++)
{
System.out.println("Cookie " + i + " name= " + cookies[i].getName());
System.out.println("Cookie " + i + " value= " +
cookies[i].getValue());
String name= cookies[i].getName();
if (name.equals("voting"))
{
cookieExists= true;
break;
}
}
}
if (!cookieExists)
{
setCookie(request,response);
... rest of servlet code
}
private void setCookie(HttpServletRequest request,
HttpServletResponse response)
{
Cookie votingCookie = new Cookie ("voting", "voted");
Calendar now= new GregorianCalendar();
Calendar tonight= new GregorianCalendar();
Date time= new Date();
now.setTime(time);
tonight.set(now.get(now.YEAR), now.get(now.MONTH),
now.get(now.DATE), 23,59);
long nowSeconds= (now.get(now.HOUR_OF_DAY) * 3600) +
(now.get(now.MINUTE) * 60);
long tonightSeconds= (tonight.get(tonight.HOUR_OF_DAY) * 3600) + (tonight.get(tonight.MINUTE) * 60);
System.out.println("Num seconds= " + ((int)(tonightSeconds - nowSeconds)) );
votingCookie.setMaxAge((int)(tonightSeconds - nowSeconds));
response.addCookie(votingCookie);
System.out.println("COokie added, name= " + votingCookie.getName());
}
-------
Relevant Standard output:
Length of cookie array= 1 (I always only get this one cookie)
Cookie 0 name= jrunsessionid
Cookie 0 value= =974499644521165506
NumSeconds= 42014 (or some other number that represents the number of seconds until midnight tonight)
Cookie added, name= voting