@RequestParam @RequestBody @PathVariable 等參數綁定__spring

來源:互聯網
上載者:User
引言:

接上一篇文章,對@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上。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.