Java spring-mvc 何时使用@CookieValue
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19281821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
spring-mvc when to use @CookieValue
提问by Frederic Close
In a controller when should you use @CookieValue ?
Only when you know that you are sure that the cookie will be present ?
在控制器中什么时候应该使用 @CookieValue ?
只有当您知道您确定 cookie 会存在时?
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.
设置 cookie 后,调用该方法没有问题,但是当未设置 cookie 时,不会调用该方法,我想我的控制器中无法将另一个方法映射到同一路径。
(my version of Spring: 3.2.3)
(我的 Spring 版本:3.2.3)
采纳答案by Frederic Close
Answered by Kal in the comment,I put the answer to mark the question as answered/closed.
由 Kal 在评论中回答,我将答案标记为已回答/已关闭。
@CookieValue
has a required parameter which is set on true by default.
@CookieValue
有一个必需参数,默认设置为 true。
So,
所以,
@CookieValue(value="myCookie", required=false)
solved my problem.
解决了我的问题。
回答by temnoi
I suppose you also can use attribute "defaultValue". It's look like:
我想你也可以使用属性“defaultValue”。它看起来像:
@CookieValue(value="name", defaultValue="someValue")
回答by teek
In my opinion:
在我看来:
cookie default
-- the logical hide the following statements from exam whether it has cookie or not because it always has one(default or not)
cookie default
-- 无论是否有 cookie,逻辑都会从检查中隐藏以下语句,因为它总是有一个(默认与否)
cookie required
-- the logical need to exam whether it has cookie and doing the corresponed action.
cookie required
-- 检查它是否有 cookie 并执行相应操作的逻辑需求。