ham*_*med 38 java cookies spring-mvc
我正在研究一个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;
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,我可以test在浏览器控制台中看到名称和值为"value" 的cookie .现在我想在其他方法中按名称获取cookie值.我怎样才能获得testcookie的价值?
mes*_*azs 79
最简单的方法是在带有@CookieValue注释的控制器中使用它:
@RequestMapping("/hello")
public String hello(@CookieValue("foo") String fooCookie) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
否则,您可以使用Spring从servlet请求中获取它 org.springframework.web.util.WebUtils
WebUtils.getCookie(HttpServletRequest request, String cookieName)
Run Code Online (Sandbox Code Playgroud)
顺便说一下,粘贴到问题中的代码可以稍微改进一下.而不是使用#setHeader(),这更优雅:
response.addCookie(new Cookie("test", "value"));
Run Code Online (Sandbox Code Playgroud)
private String extractCookie(HttpServletRequest req) {
for (Cookie c : req.getCookies()) {
if (c.getName().equals("myCookie"))
return c.getValue();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
private String getCookieValue(HttpServletRequest req, String cookieName) {
return Arrays.stream(req.getCookies())
.filter(c -> c.getName().equals(cookieName))
.findFirst()
.map(Cookie::getValue)
.orElse(null);
}
Run Code Online (Sandbox Code Playgroud)
Spring MVC 已经为您提供了该HttpServletRequest对象,它有一个getCookies()返回的方法Cookie[],因此您可以对其进行迭代。
| 归档时间: |
|
| 查看次数: |
54448 次 |
| 最近记录: |