问题
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