I'm redirecting the user to some URL and I want to send a cookie with it:
Cookie cookie = new Cookie("CADASTROADM", "someValue");
cookie.setPath("/");
cookie.setMaxAge(129600); //With it or without, makes no difference.
URL urlToRedirect = new URL(pageToRedirect);
cookie.setDomain(urlToRedirect.getHost());//With it or without, makes no difference.
response.addCookie(cookie);
response.sendRedirect(pageToRedirect);
However, when he's redirected to the page, the cookie is not there. I cannot use requestDispatcher.forward() because I'm redirecting the user to an absolute page.
Is it possible? What am I doing wrong?
Cookies can only be set/retrieved for the same domain or a subdomain as where the request is been sent to. Otherwise it's a huge security hole.
So, if you're redirecting to a different domain, then the cookie will not be available over there. If you're explicitly setting the cookie domain to that different domain, then it will be plain ignored. If you're not explicitly setting the cookie domain (and it thus defaults to the same domain as where the request is been sent to), then it would only be available for the current domain, not for the redirected domain.
You need to look for alternate ways, depending on the concrete functional requirement. It's hard to suggest one as you didn't tell anything about the concrete functional requirement in your question at all. Perhaps you should just send some specific request parameter along?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With