Spring -mvc when to use @CookieValue

In the controller, when should you use @CookieValue?
Only when you know that you are sure that a 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 a cookie is set, there is no problem called by the method, but when the cookie is not set, the method is not called, and I think that I cannot have another method in my controller that maps to the same path.

(my Spring version: 3.2.3)

+6
source share
3 answers

Answered by Kal in a comment, I put an answer to mark the question as an answer / closed.

@CookieValue has a required parameter, which is set by default by default.

So,

 @CookieValue(value="myCookie", required=false) 

solved my problem.

+11
source

I suppose you can also use the defaultValue attribute. It looks like this:

 @CookieValue(value="name", defaultValue="someValue") 
+2
source

To my mind:

cookie default - the logical concealment of the following statements from the exam: does it have a cookie or not, because it always has one (default or not)

cookie required - the logical need to check whether it has a cookie and performs the corresponding action.

+1
source

Source: https://habr.com/ru/post/955622/


All Articles