我需要在我的登录 Controller 中设置一个带重定向的 cookie。我使用下面的代码来设置 cookie。
@RequestMapping("/fbresponse")
public String getToken(@RequestParam(required = false, value = "code") String code, HttpServletResponse sResponse) {
sResponse.addCookie(new Cookie("logged", "123"));
return "redirect:"+user.getLastPage();
}
在我的索引中,我尝试使用以下代码检索 cookie:
@RequestMapping("/")
public String getIndex(@CookieValue(value="logged", required=false)String test){
user.setLastPage("/");
loginCheck();
System.out.println(test);
return "index";
}
但它始终返回 null。我尝试返回新的 ModelAndView。它也没有用,因为我需要模型中的一些组件,所以它不符合我的要求。 如何设置和检索 cookie?是否可以通过重定向来做到这一点?
更新 我的登录 Controller 中有类级别的@RequestMapping。
@Controller
@RequestMapping("/login")
public class LoginController {
@RequestMapping("/fbresponse")
public String getToken(@RequestParam(required = false, value = "code") String code, HttpServletResponse sResponse) {
sResponse.addCookie(new Cookie("logged", "123"));
return "redirect:"+user.getLastPage();
}
}
当我删除类级别请求映射时,添加 cookie 会起作用。如何使用类级别请求映射正确添加 cookie?
最佳答案
您需要set the path cookie,否则它仅对当前路径有效。
关于java - 设置 Cookie 在 Spring web-mvc 4 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35828087/