In a controller when should you use @CookieValue ?
Only when you know that you are sure that the cookie will be present ?
I have this controller:
@Controller
@RequestMapping("my")
public class MyController {
@RequestMapping("")
public ModelAndView index(@CookieValue("myCookie") String cookie,
Map<String, Object> model){
log.info("My cookie {}", cookie);
(...)
}
When the cookie is set, no problem the method is called, but when the cookie is not set the method is not called and I think I can not have another method in my controller mapped to the same path.
(my version of Spring: 3.2.3)
@SessionAttribute annotation retrieve the existing attribute from the session. This annotation allows you to tell Spring which of your model attributes will also be copied to HttpSession before rendering the view.
You can call the getCookies() method on its object to retrieve an array of Cookie objects that the client sent with this request. This method returns null if no cookies were sent. Check out how to use cookies in Spring Boot tutorial to find out more examples for reading and writing cookies in Spring Boot.
Cookies are commonly used for session management, user-tracking, and storing user preferences. Cookies are also used to recognize the client across multiple requests. Without cookies, the server would treat every request as a new client.
Answered by Kal in the comment,I put the answer to mark the question as answered/closed.
@CookieValue
has a required parameter which is set on true by default.
So,
@CookieValue(value="myCookie", required=false)
solved my problem.
I suppose you also can use attribute "defaultValue". It's look like:
@CookieValue(value="name", defaultValue="someValue")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With