11

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)

4

3 回答 3

18

Kal在评论中回答,我把答案标记为已回答/已关闭。

@CookieValue有一个必需的参数,默认情况下设置为 true。

所以,

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

解决了我的问题。

于 2013-10-09T20:52:53.953 回答
5

我想你也可以使用属性“defaultValue”。它看起来像:

@CookieValue(value="name", defaultValue="someValue")
于 2015-07-26T08:09:06.970 回答
1

在我看来:

cookie default- 逻辑隐藏以下语句从考试中是否有cookie,因为它总是有一个(默认与否)

cookie required- 检查它是否有 cookie 并执行相应操作的逻辑需要。

于 2017-06-30T10:37:20.163 回答