咱們已經學習了SpringMVC中的不少註解,好比SessionAttribute、ModelAttribute、RequestHeader等,今天咱們再介紹一個CookieValue註解。從字面意思很容易理解,@CookieValue是用於讀取Cookie值的。cookie
@CookieValue有三個參數:app
1. value:表示須要獲取的參數名,例如: JSESSIONID。默認值爲「」。學習
2. required:請求頭cookie中是否必須帶value指定的參數。默認值爲true。若是設置爲true,但請求頭cookie中不存在,則會報錯。若是設置爲false,不存在返回null。ui
3. defaultValue:若是value指定的參數不存在,或者值爲空,那麼將使用該屬性指定的默認值。默認值ValueConstants.DEFAULT_NONE。.net
使用方法和@RequestHeader相似,在controller的方法參數中使用該註解。示例以下:code
@Controller blog
public class CookieController { ip
@RequestMapping(value = "/cookieTest") get
public String getSessionId( io
@CookieValue(value = "boweifeng", required = true, defaultValue = "-1") String company,
Model model) {
model.addAttribute("company", company);
return "index";
}
}
示例紅色部分,將會讀取請求cookie,並得到boweifeng參數值,賦值給company參數。