SpringMvc動(dòng)態(tài)獲取http參數(shù)的注解詳解

SpringMVC中@RequestMapping(value="/page/{id}",method=RequestMethod.GET)中的value值可以指定處理請(qǐng)求的url、method可以指定處理請(qǐng)求的方式,SpringMvc可以通過(guò)@RequestParam@PathVariable等注解動(dòng)態(tài)獲取調(diào)用方傳來(lái)的參數(shù)。但SpringMvc獲取部分參數(shù)的注解是不相同的,下面我們就來(lái)看一下SpringMvc獲取不同部分參數(shù)的注解。

1.接收Request uri部分中參數(shù)的注解:@PathVariable;

當(dāng)使用@RequestMapping URI templeate樣式映射時(shí),即/{userId}/getById,這時(shí)的userId可通過(guò)@PathVariable注解,將它傳過(guò)來(lái)的值綁定到方法參數(shù)上。

@Controller  
@RequestMapping("/user/{userId}")  
public class RelativePathUriTemplateController {  
  
  @RequestMapping("/books/{bookId}")  
  public void findPet(@PathVariable String userId, @PathVariable String bookId) {      
  }  
}  

上面代碼將URI template中變量userId的值和bookId的值,綁定到方法的參數(shù)上。若方法的參數(shù)名稱和需要綁定的template中的變量名稱不一致,需要在@PathVariale("userId")指定uri template中的名稱。

2.接收request header部分的注解@RequestHeader,@CookieValue;

@RequestHeader注解,可以把Request請(qǐng)求中header部分的值綁定但方法參數(shù)上。

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  

Controller中使用@RequestHeader獲取header中的參數(shù):

@RequestMapping("/displayHeaderInfo.do")  
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,  
                              @RequestHeader("Keep-Alive") long keepAlive)  {  
  
  
}  

上面的代碼,將request header部分的Accept-Encoding的值,綁定到encoding上了,Keep-Alive header的值綁定到參數(shù)KeepAlive上。

@CookieValue可以將Request header中關(guān)于cookie的值綁定到方法的參數(shù)上。

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

上面就是將JSESSIONID的值綁定到參數(shù)cookie上。

3.接收request body部分的注解:@RequestParam,@RequestBody;
@RequestParam使用場(chǎng)景:
A)常用來(lái)處理簡(jiǎn)單類型的綁定,通過(guò)Reqeust.getParameter()獲取的String可以直接轉(zhuǎn)化為簡(jiǎn)單類型的情況;因?yàn)槭褂?code>request.getParameter()方式獲取參數(shù),所以可以處理get方式中queryString的值,也可以獲取Post方式中body data的值;
B)用來(lái)處理Content-Type:為application/x-www-form-urlencoded編碼的內(nèi)容,提交方式GET、POST;
C)該注解有兩個(gè)屬性:value、required;value用來(lái)指定要傳入值得id名稱,required用來(lái)指示參數(shù)是否必須綁定;

@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作用:
該注解常用來(lái)處理Content-Type:不是 application/x-www-form-urlencoded編碼的內(nèi)容,例如application/json,application/xml等; 它是通過(guò)HandlerAdapter配置的HttpMessageConverters來(lái)解析post data body,然后綁定到相應(yīng)的bean上。 因?yàn)榕渲糜?code>FormHttpMessageConverter,所以也可以用來(lái)處理Application/x-www-form-urlencoded的內(nèi)容,處理完的結(jié)果放在一個(gè)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.接收attribute類型的注解:@SessionAttributes,@ModelAttribute;
@SessionAttributes:
該注解用來(lái)綁定HttpSession中的attribute對(duì)象的值,便于在方法中的參數(shù)中使用。
該注解有value、types兩個(gè)屬性,可以通過(guò)名字和類型指定要使用的attribute對(duì)象;

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

@ModelAttribute
該注解有兩個(gè)用法:通常用來(lái)處理@RequestMapping之前,為請(qǐng)求綁定需要從后臺(tái)查詢的model;
用于參數(shù)上時(shí):用來(lái)通過(guò)名稱對(duì)應(yīng),將相應(yīng)名稱的值綁定到注解的參數(shù)bean上;要綁定的值來(lái)源于:
A)@SessionAttribute啟用的attribute對(duì)象上;
B)@ModelAttribute用于方法上時(shí)指定的model對(duì)象;
C)上述兩種情況都沒(méi)有時(shí),new一個(gè)需要綁定的bean對(duì)象,然后將request中按名稱對(duì)應(yīng)的方式把值綁定到bean中

@ModelAttribute  
public Account addAccount(@RequestParam String number) {  
    return accountManager.findAccount(number);  
}  

這種方式實(shí)際的效果就是在調(diào)用@RequestMapping的方法之前,為request對(duì)象的model里put("account",Account);

用在參數(shù)上的@ModelAttribute示例代碼:

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

首先查詢@SessionAttributes有無(wú)綁定的Pet對(duì)象,若沒(méi)有則查詢@ModelAttribute方法層面上是否綁定了Pet對(duì)象,若沒(méi)有則URI template中的值按對(duì)應(yīng)的名稱綁定到Pet對(duì)象的各屬性上。

參考文獻(xiàn):http://blog.csdn.net/walkerjong/article/details/7946109

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容