Reputation: 8033
I'm working on a java spring mvc application. I have set a cookie in one of my controller's methods in this way:
@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 test
and 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 test
cookie?
Upvotes: 55
Views: 118390
Reputation: 395
Cookie doesnt have method to get by value try this
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();
}
}
Upvotes: 1
Reputation: 16041
The simplest way is using it in a controller with the @CookieValue
annotation:
@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
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:
response.addCookie(new Cookie("test", "value"));
Upvotes: 129
Reputation: 862
private String getCookieValue(HttpServletRequest req, String cookieName) {
return Arrays.stream(req.getCookies())
.filter(c -> c.getName().equals(cookieName))
.findFirst()
.map(Cookie::getValue)
.orElse(null);
}
Upvotes: 15
Reputation: 801
private String extractCookie(HttpServletRequest req) {
for (Cookie c : req.getCookies()) {
if (c.getName().equals("myCookie"))
return c.getValue();
}
return null;
}
Upvotes: 7
Reputation: 5127
You can also use org.springframework.web.util.WebUtils.getCookie(HttpServletRequest, String)
.
Upvotes: 20
Reputation: 4310
Spring MVC already gives you the HttpServletRequest
object, it has a getCookies()
method that returns Cookie[]
so you can iterate on that.
Upvotes: 5