I have a problem with retrieving cookie value in Spring MVC web app. Project configuration is pretty basic: Eclipse and Tomcat 8.0, full Spring 4.3.9 libs, nothing fancy. I save cookies the normal way, that is:
@RequestMapping(value="/Main")
public String saveCookie(HttpServletResponse response) {
response.addCookie(new Cookie("testToken", "thisistesttoken"));
return "Profile";
}
And it does actually saves the cookie. I check in Chrome and there it is, testToken with given value. But when I try to retrieve it in my app using '@CookieValue' annotation, it gives me just the default value (or crashes when I don't declare default value):
@RequestMapping(value="/Retrieve")
public String loadCookiePage(@CookieValue(value="testToken",
defaultValue="notmyvalue") String testToken) {
System.out.println(testToken);
return "SomeOtherPage";
}
The output is:
notmyvalue
However, when I switch the code to 'HttpServletRequest' way of retrieving cookies, everything works:
@RequestMapping(value="/Retrieve")
public String loadCookiePage(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if(cookies != null) {
Arrays.stream(cookies)
.forEach(c -> System.out.println(c.getName() + " " + c.getValue()));
}
return "SomeOtherPage";
}
The output:
(...other cookies)
testToken thisistesttoken
(...)
Now I really would like to stick to '@CookieValue' annotation, since code is more readable this way. Did anyone of you encounter this problem? I tried it on different browsers, Tomcat's versions, etc., to make sure it's code related problem.