標籤:head convert http red mit cli key imp 編碼
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
- }
- }
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);
- }
java - spring mvc 之傳參@RequestParam @RequestBody @Pathvariable @RequestHeader註解