Spring MVC常用注解@PathVariable、@RequestHeader、@CookieValue、@RequestParam、@RequestBody、@SessionAttributes、@ModelAttribute


簡介:

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注解綁定它傳過來的值到方法的參數上。

示例代碼: 

@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部分:

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  
@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值:

JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84 

參數綁定的代碼:

@RequestMapping("/displayHeaderInfo.do")  
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用來指示參數是否必須綁定;

示例代碼:

@Controller  
@RequestMapping("/pets")  
@SessionAttributes("pet")  
public class EditPetForm {  
     @RequestMapping(method = RequestMethod.GET)  
     public String setupForm(@RequestParam("petId") int petId, ModelMap model) {  
       Pet pet = this.clinic.loadPet(petId);  
      model.addAttribute("pet", pet);  
      return "petForm";  
    }  
}

@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;

示例代碼:

@RequestMapping(value = "/something", method = RequestMethod.PUT)  
public void handle(@RequestBody String body, Writer writer) throws IOException {  
  writer.write(body);  
}  

4、@SessionAttributes, @ModelAttribute

@SessionAttributes

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

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

示例代碼:

@Controller  
@RequestMapping("/editPet.do")  
@SessionAttributes("pet")  
public class EditPetForm {  
    // ...   
}  

@ModelAttribute

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

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

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

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

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

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

用到方法上@ModelAttribute的示例代碼:

// Add one attribute   
// The return value of the method is added to the model under the name "account"   
// You can customize the name via @ModelAttribute("myAccount")   
  
@ModelAttribute  
public Account addAccount(@RequestParam String number) {  
    return accountManager.findAccount(number);  
} 

這種方式實際的效果就是在調用@RequestMapping的方法之前,為request對象的model里put(“account”, Account); 

用在參數上的@ModelAttribute示例代碼:

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

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

 

參考:

http://uule.iteye.com/blog/2100546(以上內容轉自此篇文章)

https://www.cnblogs.com/ruiati/p/6640007.htm

http://www.mkyong.com/webservices/jax-rs/jax-rs-pathparam-example/

https://www.cnblogs.com/chen-lhx/p/5599806.html

http://blog.sina.com.cn/s/blog_721948c20100wjqz.html

http://blog.csdn.net/u011410529/article/details/66974974


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM