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

让人想犯罪 __ 提交于 2019-12-10 18:40:01

问题


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

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.


回答1:


Try to actually add the cookie to the response:

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

See also:

  • javax.servlet.http.HttpServletResponse.addCookie(javax.servlet.http.Cookie)



回答2:


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

Try this :

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


来源:https://stackoverflow.com/questions/4456454/adding-cookie-in-java-and-then-http-redirect-doesnt-show-cookie-in-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!