首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

@RequestMapping 完整詳解:六大屬性、URI 模式與實戰範例

     編輯:Java 綜合教學

@RequestMapping 完整詳解:六大屬性、URI 模式與實戰範例

引言

專案採 REST 風格開發,POST/PUT 提交數據時發現服務端無法接收參數(未加綁定註解),請求 Content-Type 為 application/json,request.getReader() 確能讀到數據。為釐清參數綁定機制,深入研究 @RequestParam、@RequestBody、@RequestHeader、@PathVariable 及 HttpMessageConverter,於此總結。

@RequestMapping 簡介

處理請求地址映射的註解,可標註於類或方法。類上表示該類所有方法以該路徑為父路徑。六大屬性分三類說明:

1. value、method

  • value:指定請求實際地址,支援 URI Template 模式
  • method:指定 HTTP 方法(GET、POST、PUT、DELETE 等)

2. consumes、produces

  • consumes:指定處理的請求 Content-Type(如 application/json、text/html)
  • produces:指定回應 Content-Type,僅當請求頭 Accept 包含該類型時返回

3. params、headers

  • params:請求必須包含指定參數名與值
  • headers:請求必須包含指定 Header 名與值

實戰範例

value / method 範例

@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 三種模式:

  • A) 普通具體值
  • B) 含變量 URI Template:/owners/{ownerId} 搭配 @PathVariable String ownerId
  • C) 含正則:/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}

consumes / produces 範例

// 僅處理 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) { ... }

params / headers 範例

// 僅處理包含 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 等)與回應處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved