java - 在spring mvc中按名称获取cookie值

时间:2015-10-14 06:43:45

标签: java spring-mvc cookies

我正在开发一个java spring mvc应用程序。我用这种方式在我的一个控制器方法中设置了一个cookie:

@RequestMapping(value = {"/news"}, method = RequestMethod.GET)
public ModelAndView news(Locale locale, Model model, HttpServletResponse response, HttpServletRequest request) throws Exception {

    ...
    response.setHeader("Set-Cookie", "test=value; Path=/");
    ...

    modelAndView.setViewName("path/to/my/view");
    return modelAndView;
}

这很好用,我可以在浏览器控制台中看到名为test且值为“value”的cookie。现在我想在其他方法中按名称获取cookie值。如何获得test cookie的价值?

6 个答案:

答案 0 :(得分:70)

最简单的方法是在具有@CookieValue注释的控制器中使用它:

@RequestMapping("/hello")
public String hello(@CookieValue("foo") String fooCookie) {
    // ...
}

否则,您可以使用Spring org.springframework.web.util.WebUtils

从servlet请求中获取它
WebUtils.getCookie(HttpServletRequest request, String cookieName)

顺便说一下,粘贴到问题中的代码可以稍微改进一下。而不是使用#setHeader(),这更优雅:

response.addCookie(new Cookie("test", "value"));

答案 1 :(得分:9)

您也可以使用org.springframework.web.util.WebUtils.getCookie(HttpServletRequest, String)

答案 2 :(得分:4)

private String getCookieValue(HttpServletRequest req, String cookieName) {
    return Arrays.stream(req.getCookies())
            .filter(c -> c.getName().equals(cookieName))
            .findFirst()
            .map(Cookie::getValue)
            .orElse(null);
}

答案 3 :(得分:3)

Spring MVC已经为您提供了HttpServletRequest对象,它有一个返回getCookies()的{​​{1}}方法,因此您可以对其进行迭代。

答案 4 :(得分:1)

private String extractCookie(HttpServletRequest req) {
            for (Cookie c : req.getCookies()) {
               if (c.getName().equals("myCookie"))
                   return c.getValue();
               }
            return null;
        }

答案 5 :(得分:0)

Cookie没有按值获取的方法试试这个

Cookie cookie[]=request.getCookies();
Cookie cook;
String uname="",pass="";
if (cookie != null) {
for (int i = 0; i < cookie.length; i++) {
    cook = cookie[i];
    if(cook.getName().equalsIgnoreCase("loginPayrollUserName"))
            uname=cook.getValue();
    if(cook.getName().equalsIgnoreCase("loginPayrollPassword"))
            pass=cook.getValue();                   
}    
}
相关问题