简体   繁体   English

如何在response.sendRedirect()之后发送cookie?

[英]How to send a cookie after response.sendRedirect()?

I'm redirecting the user to some URL and I want to send a cookie with it: 我正在将用户重定向到某个URL,我想用它发送一个cookie:

        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. 但是,当他被重定向到页面时,cookie就不存在了。 I cannot use requestDispatcher.forward() because I'm redirecting the user to an absolute page. 我不能使用requestDispatcher.forward(),因为我正在将用户重定向到绝对页面。

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. 只能为发送请求的域或子域设置/检索Cookie。 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. 因此,如果您要重定向到其他域,那么该cookie将无法在那里使用。 If you're explicitly setting the cookie domain to that different domain, then it will be plain ignored. 如果您明确地将cookie域设置为该不同的域,那么它将被忽略。 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. 如果您没有明确设置cookie域(因此默认设置为与发送请求的域相同的域),那么它只能用于当前域,而不能用于重定向域。

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? 也许您应该发送一些特定的请求参数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM