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
常用來處理簡單類型的綁定,該注解有兩個屬性: value、required; value用來指定要傳入值的id名稱,required用來指示參數是否必須綁定;
@RequestBody
該注解常用來處理Content-Type: application/json, application/xml等內容;
