设置Cookie无法在Spring web-mvc 4中运行

paa*_*ika 3 java cookies spring spring-mvc

我需要在登录控制器中设置一个带重定向的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();
}
Run Code Online (Sandbox Code Playgroud)

在我的索引中,我尝试使用以下代码来检索cookie:

@RequestMapping("/")
public String getIndex(@CookieValue(value="logged", required=false)String test){
    user.setLastPage("/");
    loginCheck();
    System.out.println(test);
    return "index";
}
Run Code Online (Sandbox Code Playgroud)

但它总是返回null.我尝试返回新的ModelAndView.它也没有用,因为我需要模型中的一些组件,它不符合我的要求.如何设置和检索cookie?是否可以通过重定向来实现?

更新 我在登录控制器中有类级别@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();
   }
}
Run Code Online (Sandbox Code Playgroud)

当我删除类级别请求映射时添加cookie工作.如何使用类级别请求映射正确添加cookie?

JB *_*zet 11

您需要设置 cookie 的路径,否则它仅对当前路径有效.