專案採 REST 風格開發,POST/PUT 提交數據時發現服務端無法接收參數(未加綁定註解),請求 Content-Type 為 application/json,request.getReader() 確能讀到數據。為釐清參數綁定機制,深入研究 @RequestParam、@RequestBody、@RequestHeader、@PathVariable 及 HttpMessageConverter,於此總結。
處理請求地址映射的註解,可標註於類或方法。類上表示該類所有方法以該路徑為父路徑。六大屬性分三類說明:
value:指定請求實際地址,支援 URI Template 模式method:指定 HTTP 方法(GET、POST、PUT、DELETE 等)consumes:指定處理的請求 Content-Type(如 application/json、text/html)produces:指定回應 Content-Type,僅當請求頭 Accept 包含該類型時返回params:請求必須包含指定參數名與值headers:請求必須包含指定 Header 名與值@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
@RequestMapping(method = RequestMethod.GET)
public Map get() { ... }
@RequestMapping(value="/{day}", method = RequestMethod.GET)
public Map getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day) { ... }
@RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() { ... }
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) { ... }
}
value 三種模式:
/owners/{ownerId} 搭配 @PathVariable String ownerId/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}// 僅處理 Content-Type=application/json 的 POST 請求
@RequestMapping(value="/pets", method=RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) { ... }
// 僅處理 Accept 包含 application/json 的 GET 請求,暗示回應為 JSON
@RequestMapping(value="/pets/{petId}", method=RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) { ... }
// 僅處理包含 myParam=myValue 的請求
@RequestMapping(value="/pets/{petId}", method=RequestMethod.GET, params="myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { ... }
// 僅處理 Referer=https://www.ifeng.com/ 的請求
@RequestMapping(value="/pets", method=RequestMethod.GET, headers="Referer=https://www.ifeng.com/")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { ... }
下一篇將詳細講解請求數據綁定(@RequestParam、@RequestBody 等)與回應處理。