java 在java中添加cookie然后HTTP重定向不会在客户端显示cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4456454/
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-30 06:28:45  来源:igfitidea点击:

Adding cookie in java and then HTTP redirect doesnt show cookie in client side

javacookiesredirectwithcookies

提问by Tejas

I have requirement where in i need to add cookie in java and then redirect it to different URL. Now this url process should persist the cookie which i set and after its processing send it back to client. The code goes as follows

我需要在java中添加cookie然后将其重定向到不同的URL。现在这个 url 进程应该保留我设置的 cookie,并在其处理后将其发送回客户端。代码如下

Cookie cookie = new Cookie("name", "value")
// To make sure cookie is established for all the url paths
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
response.sendRedirect("someNewUrl");

Please help me regarding how can i persist the cookie throughout the redirect lifecycle and to the client. Thanks in advance.

请帮助我了解如何在整个重定向生命周期和客户端中保留 cookie。提前致谢。

回答by miku

Try to actually addthe cookie to the response:

尝试cookie实际添加到响应中:

Cookie cookie = new Cookie("user", "anonymous");
response.addCookie(cookie);

See also:

也可以看看:

回答by Vanchinathan Chandrasekaran

Did you add the cookie to the response? I'm seeing the code that just creates the cookie.

您是否将 cookie 添加到响应中?我看到的只是创建 cookie 的代码。

Try this :

试试这个 :

 Cookie c = new Cookie(name,value);
    c.setMaxAge( 3 * 30 * 24 * 60 * 60 );
    c.setPath( "/" );
    response.addCookie( c );