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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33118342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:20:58  来源:igfitidea点击:

java - get cookie value by name in spring mvc

javaspring-mvccookies

提问by hamed

I'm working on a java spring mvc application. I have set a cookie in one of my controller's methods in this way:

我正在开发一个 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;
}

This is working fine and I can see a cookie with name testand value "value" in my browser console. Now I want to get the cookie value by name in other method. How can I get value of testcookie?

这工作正常,我可以test在浏览器控制台中看到名称和值为“value”的 cookie 。现在我想通过其他方法按名称获取 cookie 值。我怎样才能获得testcookie的价值?

回答by bekce

Spring MVC already gives you the HttpServletRequestobject, it has a getCookies()method that returns Cookie[]so you can iterate on that.

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

回答by meskobalazs

The simplest way is using it in a controller with the @CookieValueannotation:

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

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

Otherwise, you can get it from the servlet request using Spring org.springframework.web.util.WebUtils

否则,您可以使用 Spring 从 servlet 请求中获取它 org.springframework.web.util.WebUtils

WebUtils.getCookie(HttpServletRequest request, String cookieName)

By the way, the code pasted into the question could be refined a bit. Instead of using #setHeader(), this is much more elegant:

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

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

回答by Vishnu Katpure

Cookie doesnt have method to get by value try this

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();                   
}    
}

回答by ryanp

You can also use org.springframework.web.util.WebUtils.getCookie(HttpServletRequest, String).

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

回答by Padi

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

回答by ottercoder

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