有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java设置Cookie在Spring webmvc 4中不起作用

我需要在我的登录控制器中设置带有重定向的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();
   }
}

当我删除类级别的请求映射时,添加cookies起作用。如何使用类级请求映射正确添加cookie


共 (1) 个答案

  1. # 1 楼答案

    您需要修改cookie的set the path,否则它只对当前路径有效