根據處理Request 的不同 分爲4種
1、處理request body部分的註解 :@RequestParam, @RequestBody
2、處理request header部分的註解: @RequestHeader, @CookieValue
3、處理requet uri 部分(這裏指uri template中variable,不含queryString部分)的註解: @PathVariable
4、處理attribute類型是註解: @SessionAttributes, @ModelAttribute
@RequestParam, @RequestBody
a、@RequestParam
1、常用來處理簡單類型的綁定,通過Request.getParameter()獲取的String可以直接轉換爲簡單類型的情況(String--> 簡單類型的轉換操作由ConversionService配置的轉換器來完成);因爲使用request.getParameter()方式獲取參數,所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值;
2、用來處理Content-Type: 爲 application/x-www-form-urlencoded
編碼的內容,提交方式GET、POST;
3、該註解有兩個屬性: 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
1、該註解常用來處理Content-Type:不是application/x-www-form-urlencoded
編碼的內容,例如application/json, application/xml等
2、它是通過使用HandlerAdapter 配置的HttpMessageConverters
來解析post data body,然後綁定到相應的bean上的。
3、因爲配置有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);
}