目錄
一、前言
二、六種參數讀取方式
1.@RequestParam
2.@PathVariable
3.@RequestBody
4.@RequestHeader
5.@CookieValue
6.@MatrixVariable
三、對比和搭配
1.適用方法類型及建議使用場景
2.建議使用的請求路徑注解
3.?多種參數同時使用
4.同一請求不同方案?
四、結語
一、前言
在 Spring Boot 開發中,接口設計與請求參數的讀取方式是每個開發者必須掌握的核心知識點。本文基于一個真實的用戶管理模塊(UserController)展開討論,深入剖析了常見的六種請求參數綁定注解(如 @RequestParam、@RequestBody 等)的使用場景、適用 HTTP 方法類型以及它們在實際開發中的最佳實踐。
通過問答的形式,我們不僅梳理了不同注解的使用差異,還探討了 RESTful 風格的設計理念、接口方法選擇的原則,以及為何在某些場景下更推薦使用 @GetMapping 而非 @PostMapping。文章內容貼近實戰,適合初學者快速入門,也適合有一定經驗的開發者進行知識體系的查漏補缺。
二、六種參數讀取方式
1.@RequestParam
1.定義:從 URL 查詢參數中獲取值
2.后端示例:
//單個參數@GetMapping("/getUserById")public UserEntity getUserById(@RequestParam("id") Integer id) {return userService.getUserById(id);}//多個參數@GetMapping("/getUserById")public UserEntity getUserById(@RequestParam("id") Integer id, @RequestParam("name") String name) {return userService.getUserById(id);}
3.前端?Axios 調用:
//單個參數
axios.get('/getUserById', { params: { id: 123 } }).then(res => console.log(res.data));
//多個參數
axios.get('/getUserById', { params: { id: 123, name: '王' } }).then(res => console.log(res.data));
?4.Postman調用:
多個參數用&隔開,如下:
2.@PathVariable
1.定義:從路徑中提取變量
2.后端示例:
//單個參數
@GetMapping("/user/{id}")
public String getUserById(@PathVariable Integer id) {return "User ID: " + id;
}
//多個參數
@GetMapping("/user/{id}/{name}")
public String getUserById(@PathVariable Integer id, @PathVariable String name) {return "User ID: " + id;
}
3.前端?Axios 調用:
//單個參數
axios.get('/user/456').then(res => console.log(res.data));
//多個參數
axios.get('/user/456/王').then(res => console.log(res.data));
4.Postman調用
多個參數用/路徑隔開。
3.@RequestBody
1.定義:從請求體中讀取 JSON 數據
2.后端示例:
@PostMapping("/addUser")public Integer addUser(@RequestBody UserEntity userEntity) {return userService.addUser(userEntity);}
3.前端Axios調用:
axios.post('/user/addUser', {name: '張三',email: 'zhangsan@example.com'
})
.then(res => console.log(res.data));
?4.Postman調用:
4.@RequestHeader
1.定義:從 HTTP 請求頭中獲取值
2.后端示例:
@GetMapping("/auth")
public String checkAuth(@RequestHeader("Authorization") String token) {return "Token: " + token;
}
3.前端Axios調用:
axios.get('/auth', {headers: { Authorization: 'Bearer token' }
})
.then(res => console.log(res.data));
4.Postman調用:
5.@CookieValue
1.定義:從 Cookie 中獲取值
2.后端示例:
@GetMapping("/profile")
public String getProfile(@CookieValue("JSESSIONID") String sessionId) {return "Session ID: " + sessionId;
}
3.前端Axios調用(瀏覽器自動攜帶 Cookie):
axios.get('/profile').then(res => console.log(res.data));
(注:前端無法直接設置 Cookie 來模擬發送,需由后端設置或在瀏覽器環境中已有該 Cookie。?)
6.@MatrixVariable
1.定義:從 URI 中提取矩陣參數(不常用)
2.后端示例:
//單個參數
@GetMapping("/users")
public String getUsersByMatrix(@MatrixVariable("type") String type) {return "Type: " + type;
}
//多個參數
@GetMapping("/users")
public String getUsersByMatrix(@MatrixVariable("type") String type,@MatrixVariable("name") String name
) {return "Type: " + type;
}
3.前端Axios調用:
多個參數用;隔開
//單個參數
axios.get('/users/2024;type=admin').then(res => console.log(res.data));
//多個參數
axios.get('/users/2024;type=admin;name=王').then(res => console.log(res.data));
4.Postman調用:
多個參數用;隔開
三、對比和搭配
1.適用方法類型及建議使用場景
2.建議使用的請求路徑注解
3.?多種參數同時使用
1.Spring MVC 支持在一個接口中混合使用多個參數注解。只要請求中提供了這些參數,就可以全部綁定到方法參數上,如下:
@GetMapping("/user/{id}")
public String getUserInfo(@PathVariable("id") Integer id,@RequestParam("name") String name,@RequestHeader("Authorization") String token,@CookieValue("JSESSIONID") String sessionId,@MatrixVariable("type") String type) {return String.format("ID: %d, Name: %s, Token: %s, Session ID: %s, Type: %s",id, name, token, sessionId, type);
}
2.?@RequestBody 不能與 @RequestParam、@PathVariable 等一起出現在同一個方法中(因為 @RequestBody 只能處理整個請求體)。
3.若使用了 @RequestBody,其他參數只能從 Header、Cookie、Path Variable 等非 Body 的地方獲取。
4.同一請求不同方案?
看了上面的注解搭配,有同學就要問了,我可以把@GetMapping+@RequestParam組合改成@PostMapping + @RequestBody啊,因為我post請求用著比較熟練,就像下面這樣:
@GetMapping("/getUserById")
public UserEntity getUserById(@RequestParam("id") Integer id)||V
public class UserIdDTO {private Integer id;// getter/setter
}@PostMapping("/getUserById")
public UserEntity getUserById(@RequestBody UserIdDTO dto) {return userService.getUserById(dto.getId());
}
答:這種方式是可以的,雖然在技術上可以都用@PostMapping+@RequestBody,在實際開發中我們遵循一些約定俗成的設計原則和 RESTful 風格,比如:
- 語義清晰:GET 表示獲取資源,POST 表示創建資源。符合 RESTful 設計規范。
- 冪等性&安全性:GET 請求是冪等且安全的(不會改變服務器狀態),更適合查詢操作。
- 緩存友好:GET 請求可以被緩存,而 POST 不會。
- 書簽/歷史記錄支持:GET 請求能保存在瀏覽器歷史或書簽中,方便調試或直接訪問。
- 簡單易測試:使用 URL 參數更容易通過瀏覽器或 Postman 直接測試。
注:以下是RESTful風格最佳實踐。
?
四、結語
通過對 UserController 示例代碼的深入分析,我們可以看到 Spring MVC 在接口設計上的靈活性與規范性并存。理解每種參數綁定方式的適用場景和限制,有助于我們在日常開發中寫出更加清晰、安全、可維護的接口。
同時,Spring 提供的 @RequestMapping 及其派生注解,為我們構建結構良好的 Web API 提供了強有力的支撐。合理地使用這些注解,不僅能提升開發效率,還能增強接口的可讀性和一致性。
希望本文能幫助你在 Spring Boot 接口設計與參數處理方面有所收獲。如果你在開發過程中也有類似疑問,歡迎留言交流,共同進步?