我正在尝试在登录后在响应中设置cookie,我想在每个其他的api调用中读取该cookie。我尝试了以下代码,但是我没有得到cookie的值..请帮助我。 。提前谢谢..
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "text/plain")
public String setCookie(HttpServletRequest request, HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException, ServiceException
{
response.addCookie(new Cookie("token", generateToken()));
return "login success";
}
@RequestMapping(value = "/getResource", method = RequestMethod.POST, consumes = "text/plain")
public String getCookie(HttpServletRequest request, HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException, ServiceException
{
Cookie[] cookies = request.getCookies();
if (cookies != null) {
Arrays.stream(cookies)
.forEach(c -> System.out.println(c.getName() + "=" + c.getValue()));
}
return "resource list";
}
答案 0 :(得分:0)
设置cookie:
Cookie cookie= new Cookie("userName", authentication.getName());
response.addCookie(cookie);
使用Cookie值:
public String hello(Model model, HttpServletRequest request, HttpServletResponse response,@CookieValue("userName") String usernameCookie) {
console.log(usernameCookie);
}
希望这会有所帮助