- @Pathvariable
public ResponseEntity<String> ordersBack( @PathVariable String reqKey, @RequestParam(value="intVal") Integer intVal, @RequestParam(value="strVal") String strVal) throws Exception{ return new ResponseEntity("ok", HttpStatus.OK); }
當使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable注解綁定它傳過來的值到方法的參數上。這樣就可以實現類似restful風格的請求。
- @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") publicclass 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"; } }
其作用實際就是將url中?后面部分請求參數作為參數的一部分。
- @RequestBody
@RequestBody 將HTTP請求正文轉換為適合的HttpMessageConverter對象。POST模式下,使用@RequestBody綁定請求對象,Spring會幫你進行協議轉換,將Json、Xml協議轉換成你需要的對象。
- @ResponseBody
@ResponseBody 將內容或對象作為 HTTP 響應正文返回,並調用適HttpMessageConverter的Adapter轉換對象,寫入輸出流。表示該方法的返回結果直接寫入HTTP response body中。
一般在異步獲取數據時使用,在使用@RequestMapping后,返回值通常解析為跳轉路徑,加上@responsebody后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP response body中。比如異步獲取json數據,加上@responsebody后,會直接返回json數據。@ResponseBody可以標注任何對象,由Srping完成對象——協議的轉換。
@Controller public class PersonController { /** * 查詢個人信息 * * @param id * @return */ @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET) public @ResponseBody Person porfile(@PathVariable int id, @PathVariable String name, @PathVariable boolean status) { return new Person(id, name, status); } /** * 登錄 * * @param person * @return */ @RequestMapping(value = "/person/login", method = RequestMethod.POST) public @ResponseBody Person login(@RequestBody Person person) { return person; } }
@InitBinder
表單中的日期 字符串和Javabean中的日期類型的屬性自動轉換, 該標簽是進行數據類型轉換的,將string類型轉為自定義的類型。
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }