@CookieValue的作用
用來獲取Cookie中的值
@CookieValue參數
1、value:參數名稱
2、required:是否必須
3、defaultValue:默認值
@CookieValue使用案例
1、我們在index.jsp頁面中創建cookie值
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <script type="text/javascript"> 7 document.cookie="name=caoyc;path=/" 8 document.cookie="age=18;path=/" 9 // 時間可以不要,但路徑(path)必須要填寫,因為JS的默認路徑是當前頁,如果不填,此cookie只在當前頁面生效!~ 10 </script> 11 12 </head> 13 14 <body> 15 <a href="testCookie">查看Cookie</a> 16 17 </body> 18 </html>
2、在控制器中
1 @RequestMapping("/testCookie") 2 public String testCookie(@CookieValue(value="name",required=false) String name, 3 @CookieValue(value="age",required=false) Integer age){ 4 System.out.println(name+","+age); 5 return "hello"; 6 }
測試代碼
測試1:
我們直接訪問http://localhost:8080/springmvc-1/testCookie
輸出結果為:null,null
測試2:
我們現在訪問http://localhost:8080/springmvc-1 這里路徑直接對應index.jsp頁面
進入頁面后通過開發者工具,我們查看到到cookie信息
然后再次訪問http://localhost:8080/springmvc-1/testCookie
結果輸出:caoyc,18