【问题标题】:Setting Cookie not working in Spring web-mvc 4设置 Cookie 在 Spring web-mvc 4 中不起作用
【发布时间】:2016-06-20 01:54:12
【问题描述】:

我需要在我的登录控制器中设置一个带有重定向的 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?是否可以通过重定向来做到这一点?

更新 我的登录控制器中有类级别的@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?

【问题讨论】:

标签: java spring spring-mvc cookies


【解决方案1】:

你需要set the path的cookie,否则只对当前路径有效。

【讨论】:

    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2011-04-13
    • 1970-01-01
    相关资源
    最近更新 更多