I'm working in a java web application that should not allow a user to open it in 2 different tabs, and I'm using session cookies for that. It seems to work fine in most scenarios, but the problem is that the cookies are not cleared when the browsers exits. This is how I set the cookies:
String sCookie = "mycookie=true;Path=/;Domain=.mydomain.com;HttpOnly";
if (!response.containsHeader("Set-Cookie")) {
response.setHeader("Set-Cookie", sCookie);
} else {
response.addHeader("Set-Cookie", sCookie);
}
As I understand, if I don't specify the Expires field, the cookie should be deleted on browser close. This is how I validate if the cookie exists:
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("mycookie".equals(cookie.getName()) && Boolean.valueOf(cookie.getValue())) {//some error}}
Is there any problem with this code? meaning, can I set the cookie with response.setHeader
and then check it with request.getCookies()
?
Sometimes I have problems deleting the cookie manually and then when I restart the browser the problem continues.
This is how I manually delete the cookie (on tab close):
String sCookie = "mycookie=;Path=/;Domain=.mydomain.com;HttpOnly";
if (!response.containsHeader("Set-Cookie")) {
response.setHeader("Set-Cookie", sCookie);
} else {
response.addHeader("Set-Cookie", sCookie);
}
Thanks in advance
UPDATE
This is how I create the cookie:
Cookie c = new Cookie("mycookie","true");
c.setDomain(".mydomain.com");
c.setPath("/");
c.setValue("true");
response.addCookie(c);
This is how I delete the cookie:
for (Cookie c : request.getCookies()) {
if ("mycookie".equals(c.getName())) {
c.setMaxAge(0);
c.setValue("");
}
}
But still not working. Actually, now the cookie is not deleted when I close the tab (this was working fine in my previous version with "Set-Cookie" :S).Another detail is that I'm not seeing my cookie in the Resources tab of Chrome's developer tools