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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11872896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:44:54  来源:igfitidea点击:

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

javaservletsredirectcookies

提问by thevoyager

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. I cannot use requestDispatcher.forward() because I'm redirecting the user to an absolute page.

但是,当他重定向到该页面时,cookie 并不存在。我不能使用 requestDispatcher.forward() 因为我将用户重定向到一个绝对页面。

Is it possible? What am I doing wrong?

是否可以?我究竟做错了什么?

回答by BalusC

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.

只能为与请求发送到的域或子域相同的域或子域设置/检索 Cookie。否则这是一个巨大的安全漏洞。

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.

因此,如果您要重定向到不同的域,则 cookie 将无法在那里使用。如果您明确地将 cookie 域设置为不同的域,那么它将被完全忽略。如果您没有明确设置 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?

您需要根据具体的功能需求寻找替代方法。很难提出一个建议,因为您根本没有说明问题中的具体功能要求。也许您应该只发送一些特定的请求参数?