@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletResponse response, Model modelAndView, @RequestParam String email, @RequestParam String password, @RequestParam(required = false) String redirect) {
LoginDTO loginDTO = account.doLogin(email, password);
if (loginDTO.getLoginMGS() == LoginStatus.LOGGED_IN) {
Cookie cookie = new Cookie("token", loginDTO.getToken());
cookie.setMaxAge(24 * 60 * 60);
response.addCookie(cookie);
modelAndView.addAttribute("result", "Login successful");
if (redirect != null && !redirect.equals("")) {
return "redirect:" + redirect;
}
} else {
modelAndView.addAttribute("result", "Password not same");
}
return "login";
}
当我尝试像这样获取cookie时
private String getToken(Cookie[] cookies) {
for (Cookie cookie : cookies) {
System.out.println("cookie name " + cookie.getName() + " " + cookie.getValue());
if (cookie.getName().equals("token")) {
return cookie.getValue();
}
}
return null;
}
打印:cookie名称fm-shopify-session S%3AsYalW2cHkgglgGNQDfQ3o2hhHAK_7Lrv.pulogz2rfpYWGtZL26K13%2FU6sW7wqUwdKNnvpLgplq8
它不包含令牌
答案 0 :(得分:1)
如果要在两次请求之间访问Cookie,则必须指定路径details
Cookie cookie = new Cookie("token", loginDTO.getToken());
cookie.setMaxAge(24 * 60 * 60);
cookie.setPath(path);
response.addCookie(cookie);
答案 1 :(得分:1)
在我的情况下,未创建cookie是因为当我在没有https的本地主机上时cookie是“安全的”
cookie.setSecure(true)