引言:
接上一篇文章,對@RequestMapping進行地址映射講解之後,該篇主要講解request 資料到handler method 參數資料的綁定所用到的註解和什麼情形下使用;
簡介:
handler method 參數綁定常用的註解,我們根據他們處理的Request的不同內容部分分為四類:(主要講解常用類型)
A、處理requet uri 部分(這裡指uri template中variable,不含queryString部分)的註解: @PathVariable;
B、處理request header部分的註解: @RequestHeader, @CookieValue;
C、處理request body部分的註解:@RequestParam, @RequestBody;
D、處理attribute類型是註解: @SessionAttributes, @ModelAttribute;
1、 @PathVariable
當使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable註解綁定它傳過來的值到方法的參數上。
範例程式碼: [java] view plain copy ? @Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping("/pets/{petId}") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { // implementation omitted } } 上面代碼把URI template 中變數 ownerId的值和petId的值,綁定到方法的參數上。若方法參數名稱和需要綁定的uri template中變數名稱不一致,需要在@PathVariable("name")指定uri template中的名稱。
2、 @RequestHeader、@CookieValue
@RequestHeader 註解,可以把Request請求header部分的值綁定到方法的參數上。
範例程式碼:
這是一個Request 的header部分: [plain] view plain copy ? Host localhost:8080 Accept text/html,application/xhtml+xml,application/xml;q=0.9 Accept-Language fr,en-gb;q=0.7,en;q=0.3 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 300
[java] view plain copy ? @RequestMapping("/displayHeaderInfo.do") public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) { //... } 上面的代碼,把request header部分的 Accept-Encoding的值,綁定到參數encoding上了, Keep-Alive header的值綁定到參數keepAlive上。
@CookieValue 可以把Request header中關於cookie的值綁定到方法的參數上。
例如有如下Cookie值:
[java] view plain copy ? JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84 參數綁定的代碼: [java] view plain copy ? @RequestMapping("/displayHeaderInfo.do") public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) { //... } 即把JSESSIONID的值綁定到參數cookie上。