概述
Spring從2.5版本開始引入註解,雖然版本不斷變化,可是註解的特性一直被延續下來並不斷進行擴展,這裏就來記錄一下Spring MVC中經常使用的註解,本文承接前文繼續記錄@PathVariable、@RequestHeader和@CookieValue三個註解。瀏覽器
@PathVariable註解
該註解能夠方便的得到請求URL中的動態參數。只有一個屬性value,類型爲String,表示綁定的名稱,若省略默認綁定同名參數。
cookie
1 @RequestMapping(value = "/login/{username}") 2 public String login(@PathVariable String username){ 3 ... 4 }
若請求的URL爲:「http://localhost:8080/user/login/jack」,經過該註解將jack綁定到username參數上。
@RequestHeader註解
該註解用於將請求頭信息數據映射到功能處理方法的參數。
@RequestHeader註解支持的經常使用屬性:session
屬性 | 類型 | 說明 |
name | String | 指定請求頭綁定的名稱 |
value | String | name屬性的別名 |
required | boolean | 參數是否必須綁定 |
defaultValue | String | 沒有傳遞參數時,參數的默認值 |
@CookieValue註解
該註解用於將請求的Cookie數據映射到功能處理方法的參數。
@CookieValue註解支持的經常使用屬性:app
屬性 | 類型 | 說明 |
name | String | 指定請求頭綁定的名稱 |
value | String | name屬性的別名 |
required | boolean | 參數是否必須綁定 |
defaultValue | String | 沒有傳遞參數時,參數的默認值 |
註解示例程序
示例程序在前文項目SpringMVCProject的基礎上進行完善編寫。
在com.snow.dcl.controller包下建立DataBindController類文件,編寫以下程序:
jsp
1 @Controller 2 public class DataBindController { 3 private static final Log LOGGER = LogFactory.getLog(DataBindController.class); 4 5 @RequestMapping("/PathVariableTest/{userId}") 6 public void pathVariableTest(@PathVariable Integer userId) { 7 LOGGER.info("經過@PathVariable獲取數據" + userId); 8 } 9 10 @RequestMapping("/RequestHeaderTest") 11 public void requestHeaderTest(@RequestHeader("User-Agent") String userAgent) { 12 LOGGER.info("經過@RequestHeader獲取數據" + userAgent); 13 } 14 15 @RequestMapping("/CookieValueTest") 16 public void cookieValueTest(@CookieValue(defaultValue = "DCLSNOWID") String sessionId) { 17 LOGGER.info("經過@CookieValue獲取數據" + sessionId); 18 } 19 } 20
啓動TomcatServer,啓動完成後,打開瀏覽器輸入:http://localhost:8080/PathVariableTest/1001,雖然瀏覽器頁面會報404的錯誤,是由於沒有返回的jsp文件,可是看控制檯打印的日誌信息便可。
ui
1 信息 [http-nio-8080-exec-6] com.snow.dcl.controller.DataBindController.pathVariableTest 經過@PathVariable獲取數據1001
1 信息 [http-nio-8080-exec-9] com.snow.dcl.controller.DataBindController.requestHeaderTest 經過@RequestHeader獲取數據Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
1 信息 [http-nio-8080-exec-2] com.snow.dcl.controller.DataBindController.cookieValueTest 經過@CookieValue獲取數據DCLSNOWID