@PathVariable和@RequestParam的區別

來源:互聯網
上載者:User

標籤:blog   http   java   使用   os   strong   

請求路徑上有個id的變數值,可以通過@PathVariable來擷取  @RequestMapping(value = "/page/{id}", method = RequestMethod.GET) 
@RequestParam用來獲得靜態URL請求入參     spring註解時action裡用到。

簡介:

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 plaincopyprint?

  1. @Controller
  2. @RequestMapping("/owners/{ownerId}") 
  3. public class RelativePathUriTemplateController { 
  4. @RequestMapping("/pets/{petId}") 
  5. public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {     
  6. // implementation omitted
  7.   } 

上面代碼把URI template 中變數 ownerId的值和petId的值,綁定到方法的參數上。若方法參數名稱和需要綁定的uri template中變數名稱不一致,需要在@PathVariable("name")指定uri template中的名稱。

2、 @RequestHeader、@CookieValue

@RequestHeader 註解,可以把Request請求header部分的值綁定到方法的參數上。

範例程式碼:

這是一個Request 的header部分:

  1. Host                    localhost:8080 
  2. Accept                  text/html,application/xhtml+xml,application/xml;q=0.9 
  3. Accept-Language         fr,en-gb;q=0.7,en;q=0.3 
  4. Accept-Encoding         gzip,deflate 
  5. Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7 
  6. Keep-Alive              300 
  1. @RequestMapping("/displayHeaderInfo.do") 
  1. public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, 
  2. @RequestHeader("Keep-Alive") long keepAlive)  { 

上面的代碼,把request header部分的 Accept-Encoding的值,綁定到參數encoding上了, Keep-Alive header的值綁定到參數keepAlive上。

@CookieValue 可以把Request header中關於cookie的值綁定到方法的參數上。

例如有如下Cookie值:

  1. JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

參數綁定的代碼:

  1. @RequestMapping("/displayHeaderInfo.do") 
  2. public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  { 

即把JSESSIONID的值綁定到參數cookie上。

3、@RequestParam, @RequestBody

@RequestParam

A) 常用來處理簡單類型的綁定,通過Request.getParameter() 擷取的String可直接轉換為簡單類型的情況( String--> 簡單類型的轉換操作由ConversionService配置的轉換器來完成);因為使用request.getParameter()方式擷取參數,所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值

B)用來處理Content-Type: 為 application/x-www-form-urlencoded編碼的內容,提交方式GET、POST;

C) 該註解有兩個屬性: value、required; value用來指定要傳入值的id名稱,required用來指示參數是否必須綁定;

範例程式碼:

  1. @Controller
  2. @RequestMapping("/pets") 
  3. @SessionAttributes("pet") 
  4. public class EditPetForm { 
  5. @RequestMapping(method = RequestMethod.GET) 
  6. public String setupForm(@RequestParam("petId") int petId, ModelMap model) { 
  7.        Pet pet = this.clinic.loadPet(petId); 
  8.    model.addAttribute("pet", pet); 
  9. return "petForm"; 
  10.    } 

@RequestBody

該註解常用來處理Content-Type: 不是application/x-www-form-urlencoded編碼的內容,例如application/json, application/xml等;

它是通過使用HandlerAdapter 配置的HttpMessageConverters來解析post data body,然後綁定到相應的bean上的。

因為配置有FormHttpMessageConverter,所以也可以用來處理 application/x-www-form-urlencoded的內容,處理完的結果放在一個MultiValueMap<String, String>裡,這種情況在某些特殊需求下使用,詳情查看FormHttpMessageConverter api;

範例程式碼:

[java] view plaincopyprint?

  1. @RequestMapping(value = "/something", method = RequestMethod.PUT) 
  2. public void handle(@RequestBody String body, Writer writer) throws IOException { 
  3.   writer.write(body); 
4、@SessionAttributes, @ModelAttribute

@SessionAttributes:

該註解用來綁定HttpSession中的attribute對象的值,便於在方法中的參數裡使用。

該註解有value、types兩個屬性,可以通過名字和類型指定要使用的attribute 對象;

範例程式碼:

[java] view plaincopyprint?

  1. @Controller
  2. @RequestMapping("/editPet.do") 
  3. @SessionAttributes("pet") 
  4. public class EditPetForm { 
  5. // ...

@ModelAttribute

該註解有兩個用法,一個是用於方法上,一個是用於參數上;

用於方法上時:  通常用來在處理@RequestMapping之前,為請求綁定需要從後台查詢的model;

用於參數上時: 用來通過名稱對應,把相應名稱的值綁定到註解的參數bean上;要綁定的值來源於:

A) @SessionAttributes 啟用的attribute 對象上;

B) @ModelAttribute 用於方法上時指定的model對象;

C) 上述兩種情況都沒有時,new一個需要綁定的bean對象,然後把request中按名稱對應的方式把值綁定到bean中。

用到方法上@ModelAttribute的範例程式碼:

[java] view plaincopyprint?

  1. // Add one attribute
  2. // The return value of the method is added to the model under the name "account"
  3. // You can customize the name via @ModelAttribute("myAccount")
  4. @ModelAttribute
  5. public Account addAccount(@RequestParam String number) { 
  6. return accountManager.findAccount(number); 
  7. }
  8. 這種方式實際的效果就是在調用@RequestMapping的方法之前,為request對象的model裡put(“account”, Account);

用在參數上的@ModelAttribute範例程式碼:

[java] view plaincopyprint?

  1. @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST) 
  2. public String processSubmit(@ModelAttribute Pet pet) { 

首先查詢 @SessionAttributes有無綁定的Pet對象,若沒有則查詢@ModelAttribute方法層面上是否綁定了Pet對象,若沒有則將URI template中的值按對應的名稱綁定到Pet對象的各屬性上。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.