Spring MVC映射HTTP請求到Controller的處理方法
請求映射的核心:@RequestMapping 注解
@RequestMapping 是 Spring MVC 中最核心、最通用的映射注解。它可以用于類級別(Class-level)和方法級別(Method-level)。
類級別映射 (Class-level Mapping):
- 當(dāng)
@RequestMapping應(yīng)用在類上時(shí),它定義了Controller 處理所有請求的基類URL 路徑。 - 這樣可以避免在每個(gè)方法上添加重復(fù)相同的路徑前綴。
- 當(dāng)
方法級別映射 (Method-level Mapping):
- 當(dāng)
@RequestMapping應(yīng)用在方法上時(shí),它指定了該方法具體處理哪個(gè)(或哪些)URL 路徑的請求。 - 這個(gè)路徑是相對于類級別路徑的(如果存在的話)。
- 當(dāng)
@RequestMapping 的主要屬性:
value或path:- 指定映射的 URL 路徑??梢允且粋€(gè)字符串?dāng)?shù)組,表示映射多個(gè)路徑到同一個(gè)方法。
- 支持 Ant 風(fēng)格的路徑模式(如
*,**,?)和 URI 模板變量(路徑變量,如{userId})。 value和path是同義詞,可以互換使用。
method:- 指定該方法處理的 HTTP 請求方法(GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE)。
- 可以是一個(gè)
RequestMethod枚舉值的數(shù)組,表示處理多種 HTTP 方法。 - 如果不指定,默認(rèn)會匹配 所有 HTTP 方法。
params:- 根據(jù)請求參數(shù)(Query Parameters 或 Form Data)進(jìn)行映射。只有當(dāng)請求中包含(或不包含,或具有特定值)指定的參數(shù)時(shí),才會匹配成功。
- 表達(dá)式語法:
"myParam": 參數(shù)myParam必須存在。"!myParam": 參數(shù)myParam必須不存在。"myParam=myValue": 參數(shù)myParam必須存在且值為myValue。"myParam!=myValue": 參數(shù)myParam必須存在且值不為myValue。- 可以組合多個(gè)條件,如
{"myParam=val", "otherParam"}(AND 關(guān)系)。
headers:- 根據(jù)請求頭(Request Headers)進(jìn)行映射。只有當(dāng)請求包含(或不包含,或具有特定值)指定的頭信息時(shí),才會匹配成功。
- 語法與
params類似,如"Accept=application/json","!User-Agent","X-Custom-Header=value"。
consumes:- 指定該方法能夠處理的請求的
Content-Type(即客戶端發(fā)送的數(shù)據(jù)類型)。只有當(dāng)請求的Content-TypeHeader 與指定的值匹配時(shí),才會映射成功。 - 例如:
consumes = "application/json"或consumes = MediaType.APPLICATION_JSON_VALUE??梢灾付ǘ鄠€(gè),如{"application/json", "application/xml"}。
- 指定該方法能夠處理的請求的
produces:- 指定該方法能夠生成的響應(yīng)的
Content-Type(即服務(wù)器返回的數(shù)據(jù)類型)。Spring 會根據(jù)請求的AcceptHeader 和此屬性進(jìn)行內(nèi)容協(xié)商(Content Negotiation),選擇最合適的HttpMessageConverter來序列化返回值。 - 例如:
produces = "application/json"或produces = MediaType.APPLICATION_JSON_VALUE??梢灾付ǘ鄠€(gè)。
- 指定該方法能夠生成的響應(yīng)的
示例:使用 @RequestMapping
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;
@Controller
@RequestMapping("/users") // 類級別映射,所有方法都在 /users 路徑下
public class UserController {
// 映射 GET /users/{id}
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody // 如果用 @Controller 需要加這個(gè)來返回?cái)?shù)據(jù)
public User getUser(@PathVariable Long id) {
// ... 獲取用戶邏輯 ...
return new User(id, "Example User");
}
// 映射 POST /users
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String createUser(@RequestBody User newUser) {
// ... 創(chuàng)建用戶邏輯 ...
return "User created";
}
// 映射 GET /users?admin=true (需要 admin 參數(shù))
@RequestMapping(method = RequestMethod.GET, params = "admin=true")
@ResponseBody
public String getAdminUsers() {
// ... 獲取管理員用戶列表 ...
return "List of Admin Users";
}
// 映射 GET /users (只接受 JSON 請求)
@RequestMapping(method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public String getUsersAcceptingJson() {
// ... 獲取用戶列表 ...
return "List of Users (JSON requested)";
}
}
@RequestMapping 的變體 (快捷方式注解)
為了提高代碼的可讀性和簡潔性,Spring 提供了針對特定 HTTP 方法的快捷方式注解。它們本質(zhì)上是 @RequestMapping 預(yù)設(shè)了 method 屬性的別名。
@GetMapping: 映射 HTTP GET 請求。等價(jià)于@RequestMapping(method = RequestMethod.GET)。@PostMapping: 映射 HTTP POST 請求。等價(jià)于@RequestMapping(method = RequestMethod.POST)。@PutMapping: 映射 HTTP PUT 請求。等價(jià)于@RequestMapping(method = RequestMethod.PUT)。@DeleteMapping: 映射 HTTP DELETE 請求。等價(jià)于@RequestMapping(method = RequestMethod.DELETE)。@PatchMapping: 映射 HTTP PATCH 請求。等價(jià)于@RequestMapping(method = RequestMethod.PATCH)。
這些快捷注解也支持 @RequestMapping 的 value/path, params, headers, consumes, produces 屬性。
使用快捷方式注解的優(yōu)點(diǎn):
- 更簡潔: 代碼更短。
- 更清晰: 一眼就能看出方法處理的是哪種 HTTP 請求。
示例:使用快捷方式注解 (@RestController 簡化)
import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;
@RestController // 使用 @RestController,無需在每個(gè)方法上加 @ResponseBody
@RequestMapping("/api/items") // 類級別映射
public class ItemController {
// 映射 GET /api/items/{itemId}
// produces 也可直接寫字符串
@GetMapping(value = "/{itemId}", produces = MediaType.APPLICATION_JSON_VALUE)
public Item getItem(@PathVariable String itemId) {
// ... 獲取物品邏輯 ...
return new Item(itemId, "Sample Item");
}
// 映射 POST /api/items
// consumes 可以指定多個(gè)
@PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public String createItem(@RequestBody Item newItem) {
// ... 創(chuàng)建物品邏輯 ...
return "Item created: " + newItem.getName();
}
// 映射 PUT /api/items/{itemId}
@PutMapping("/{itemId}")
public Item updateItem(@PathVariable String itemId, @RequestBody Item updatedItem) {
// ... 更新物品邏輯 ...
updatedItem.setId(itemId); // 假設(shè)更新成功
return updatedItem;
}
// 映射 DELETE /api/items/{itemId}
@DeleteMapping("/{itemId}")
public String deleteItem(@PathVariable String itemId) {
// ... 刪除物品邏輯 ...
return "Item deleted: " + itemId;
}
// 映射 GET /api/items?type=gadget
@GetMapping(params = "type=gadget")
public String getGadgets() {
return "List of Gadgets";
}
// 映射 GET /api/items (需要特定 Header)
@GetMapping(headers = "X-API-Version=2")
public String getItemsV2() {
return "List of Items (API V2)";
}
}
// 示例 Pojo
class Item {
private String id;
private String name;
// constructors, getters, setters...
public Item(String id, String name) { this.id = id; this.name = name; }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
class User {
private Long id;
private String username;
// constructors, getters, setters...
public User(Long id, String username) { this.id = id; this.username = username; }
public Long getId() { return id; }
public String getUsername() { return username; }
}
總結(jié)
@RequestMapping是基礎(chǔ),可以映射任何 HTTP 方法,并提供最全面的配置選項(xiàng)(path,method,params,headers,consumes,produces)。@GetMapping,@PostMapping,@PutMapping,@DeleteMapping,@PatchMapping是針對特定 HTTP 方法的快捷方式,使代碼更簡潔明了,是目前 Spring MVC/WebFlux 開發(fā)中的推薦用法。- 可以在類級別和方法級別同時(shí)使用映射注解,類級別定義基礎(chǔ)路徑,方法級別定義相對路徑。
- URL 路徑通過
value或path屬性匹配,支持模式和路徑變量 ({var})。 - HTTP 方法通過
method屬性(在@RequestMapping中)或選擇特定的快捷注解(如@GetMapping)來匹配。 - 請求參數(shù)通過
params屬性進(jìn)行匹配。 - 請求頭通過
headers屬性進(jìn)行匹配。 - 請求體類型 (
Content-Type) 通過consumes屬性進(jìn)行匹配。 - 可接受的響應(yīng)類型 (
Accept) 通過produces屬性參與內(nèi)容協(xié)商。
以上就是Spring MVC映射HTTP請求到Controller的處理方法的詳細(xì)內(nèi)容,更多關(guān)于Spring MVC映射HTTP到Controller的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java?設(shè)計(jì)模式從風(fēng)控鏈理解責(zé)任鏈模式
這篇文章主要為大家介紹了java?設(shè)計(jì)模式從風(fēng)控鏈理解責(zé)任鏈模式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
解決工具接口調(diào)用報(bào)錯(cuò):error:Unsupported Media Type問題
當(dāng)遇到"UnsupportedMediaType"錯(cuò)誤時(shí),意味著HTTP請求的Content-Type與服務(wù)器期望的不匹配,比如服務(wù)器期待接收J(rèn)SON格式數(shù)據(jù),而發(fā)送了純文本格式,常見的Content-Type類型包括text/html、application/json、multipart/form-data等2024-10-10
詳解Spring Cloud微服務(wù)架構(gòu)下的WebSocket解決方案
這篇文章主要介紹了詳解Spring Cloud微服務(wù)架構(gòu)下的WebSocket解決方案,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12
淺談SpringBoot集成Redis實(shí)現(xiàn)緩存處理(Spring AOP實(shí)現(xiàn))
這篇文章主要介紹了淺談SpringBoot集成Redis實(shí)現(xiàn)緩存處理(Spring AOP實(shí)現(xiàn)),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12
Springboot項(xiàng)目參數(shù)校驗(yàn)方式(Validator)
本文介紹了如何在Spring Boot項(xiàng)目中使用`spring-boot-starter-validation`包和注解來實(shí)現(xiàn)請求參數(shù)校驗(yàn),主要介紹了校驗(yàn)注解的使用方法、校驗(yàn)失敗的異常捕獲以及`@Validated`的分組功能2025-02-02

