Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring-mvc when to use @CookieValue

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)

like image 824
Frederic Close Avatar asked Oct 09 '13 20:10

Frederic Close


People also ask

What is @sessionattributes in Spring MVC?

@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.

How do you value cookies in Spring?

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.

What is session cookie 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.


2 Answers

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.

like image 110
Frederic Close Avatar answered Nov 03 '22 23:11

Frederic Close


I suppose you also can use attribute "defaultValue". It's look like:

@CookieValue(value="name", defaultValue="someValue")
like image 39
temnoi Avatar answered Nov 04 '22 00:11

temnoi