SpringBoot接口獲取參數(shù)的常用注解詳解
SpringBoot 接口獲取參數(shù)的注解非常豐富,下面詳細(xì)介紹一下常用的參數(shù)注解:
1、URL 路徑參數(shù)
@PathVariable
獲取 URL 路徑中的參數(shù)
// 獲取單個(gè)參數(shù)
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
// 獲取多個(gè)參數(shù)
@GetMapping("/user/{id}/post/{postId}")
public String getInfo(
@PathVariable Long id,
@PathVariable Long postId
) {
// ...
}
// 參數(shù)名不一致時(shí)指定
@GetMapping("/user/{userId}")
public User getUser(@PathVariable("userId") Long id) {
return userService.findById(id);
}
// 獲取所有路徑變量(Map形式)
@GetMapping("/user/{id}/post/{postId}")
public String getInfo(@PathVariable Map<String, String> pathVariables) {
return pathVariables.get("id");
}
// URL路徑中的時(shí)間參數(shù)
@GetMapping("/events/date/{date}")
public List<Event> getEventsByPathDate(
@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
return eventService.findByDate(date);
}
@GetMapping("/events/datetime/{datetime}")
public String getByDateTime(
@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime datetime) {
return "時(shí)間: " + datetime;
}
2. 查詢參數(shù)(URL 參數(shù))
@RequestParam
獲取 URL 查詢字符串參數(shù)
// 必填參數(shù)
@GetMapping("/users")
public List<User> getUsers(@RequestParam String name) {
return userService.findByName(name);
}
// 可選參數(shù)
@GetMapping("/users")
public List<User> getUsers(
@RequestParam(required = false) String name,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size
) {
return userService.findByName(name, page, size);
}
// 接收多個(gè)值
@GetMapping("/users")
public List<User> getUsers(@RequestParam List<Long> ids) {
return userService.findByIds(ids);
}
// 獲取所有查詢參數(shù)(Map形式)
@GetMapping("/search")
public String search(@RequestParam Map<String, String> params) {
return params.get("keyword");
}
// 查詢參數(shù)中的時(shí)間
@GetMapping("/events")
public List<Event> getEventsByDate(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
return eventService.findByDate(date);
}
// 多個(gè)時(shí)間參數(shù)
@GetMapping("/events/range")
public List<Event> getEventsByRange(
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
return eventService.findByDateRange(startDate, endTime);
}
3. 請(qǐng)求體參數(shù)
@RequestBody
獲取 JSON/XML 格式的請(qǐng)求體
@PostMapping("/user")
public User createUser(@RequestBody User user) {
return userService.save(user);
}
// 接收 Map 類型的請(qǐng)求體
@PostMapping("/data")
public String processData(@RequestBody Map<String, Object> data) {
return data.toString();
}
// 使用 DTO 接收參數(shù)
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody RegisterDTO registerDTO) {
// 處理注冊(cè)邏輯
return ResponseEntity.ok("注冊(cè)成功");
}
@ModelAttribute
獲取表單數(shù)據(jù)(支持 GET/POST)
// 綁定到對(duì)象
@PostMapping("/user")
public String createUser(@ModelAttribute User user) {
userService.save(user);
return "success";
}
// 綁定到 Map
@PostMapping("/user")
public String createUser(@ModelAttribute Map<String, Object> model) {
return model.get("name").toString();
}
4. 請(qǐng)求頭參數(shù)
@RequestHeader
獲取 HTTP 請(qǐng)求頭信息
@GetMapping("/info")
public String getInfo(
@RequestHeader("User-Agent") String userAgent,
@RequestHeader(value = "Authorization", required = false) String auth,
@RequestHeader Map<String, String> headers
) {
return "User-Agent: " + userAgent;
}
5. Cookie 參數(shù)
@CookieValue
獲取 Cookie 中的值
@GetMapping("/profile")
public String getProfile(@CookieValue("sessionId") String sessionId) {
return "Session ID: " + sessionId;
}
// 可選參數(shù)
@GetMapping("/profile")
public String getProfile(
@CookieValue(value = "sessionId", defaultValue = "default") String sessionId
) {
return "Session ID: " + sessionId;
}
6. 文件上傳參數(shù)
@RequestPart
獲取文件上傳內(nèi)容
@RequestPart處理 multipart/form-data 請(qǐng)求中的復(fù)雜數(shù)據(jù)類型,支持文件上傳和混合表單數(shù)據(jù)(如 JSON + 文件)。
| 特性 | @RequestPart | @RequestParam |
|---|---|---|
| 數(shù)據(jù)格式 | 支持任何內(nèi)容類型(如 JSON、XML) | 僅支持 application/x-www-form-urlencoded |
| 內(nèi)容類型 | 每個(gè)部分有獨(dú)立的 Content-Type | 整個(gè)請(qǐng)求統(tǒng)一的 Content-Type |
| 數(shù)據(jù)處理 | 使用 HttpMessageConverter | 使用 Servlet API 的參數(shù)解析 |
| 文件處理 | 天然支持文件上傳,支持其他類型 | 僅支持文件(作為 MultipartFile) |
| JSON 綁定 | 直接綁定到對(duì)象 | 不支持 |
| 主要應(yīng)用場(chǎng)景 | 上傳文件同時(shí)發(fā)送 JSON 數(shù)據(jù):如用戶上傳頭像并附帶用戶信息(JSON)。 單個(gè)請(qǐng)求中混合不同類型的數(shù)據(jù):如同時(shí)上傳多個(gè)文件和表單數(shù)據(jù)。 REST API 中的文件上傳:如上傳圖片并附帶元數(shù)據(jù)(JSON)。 |
@RestController
@RequestMapping("/api/upload")
public class UploadController {
// 基礎(chǔ)文件上傳
@PostMapping("/single")
public String uploadSingle(@RequestPart("file") MultipartFile file) {
return "Uploaded: " + file.getOriginalFilename();
}
// 多文件上傳
@PostMapping("/multiple")
public String uploadMultiple(@RequestPart("files") MultipartFile[] files) {
return "Uploaded " + files.length + " files";
}
// 文件 + JSON對(duì)象
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadData(@RequestPart("file") MultipartFile file,
@RequestPart("metadata") MyMetadata metadata) {
// metadata 是自定義的 JSON 對(duì)象
return "Uploaded file with metadata";
}
// 文件 + 表單字段
@PostMapping(value = "/upload-with-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> uploadWithData(
@RequestPart("file") MultipartFile file,
@RequestParam("name") String name,
@RequestParam("description") String description) {
// 處理文件和文本數(shù)據(jù)
return ResponseEntity.ok("上傳成功");
}
}
常見錯(cuò)誤及解決方法:
- 忘記設(shè)置 consumes = "multipart/form-data":導(dǎo)致無法解析請(qǐng)求。
- 文件大小超過默認(rèn)限制:需配置 spring.servlet.multipart.max-file-size 和 spring.servlet.multipart.max-request-size。
與 @RequestBody 的區(qū)別:
- @RequestBody 用于處理 application/json 或 application/xml 格式的請(qǐng)求體數(shù)據(jù)。
- @RequestPart 用于處理 multipart/form-data 中的復(fù)雜數(shù)據(jù)類型(如 JSON + 文件)。
@RequestParam
@PostMapping("/upload-simple")
public String uploadSimple(@RequestParam("file") MultipartFile file) {
return "文件名稱: " + file.getOriginalFilename();
}
7. 會(huì)話和屬性參數(shù)
@SessionAttribute
獲取會(huì)話屬性
@GetMapping("/dashboard")
public String dashboard(@SessionAttribute("user") User user) {
return "歡迎 " + user.getUsername();
}
@RequestAttribute
獲取請(qǐng)求域?qū)傩?/p>
@GetMapping("/process")
public String process(@RequestAttribute("processedData") String data) {
return "處理后的數(shù)據(jù): " + data;
}
8. 其他特殊注解
@MatrixVariable
獲取矩陣變量(不常用)
// URL: /cars;color=red;year=2023
@GetMapping("/cars")
public String getCar(@MatrixVariable String color) {
return color;
}
@Value(從配置獲?。?/strong>
@GetMapping("/config")
public String getConfig(@Value("${app.name}") String appName) {
return "應(yīng)用名稱: " + appName;
}
到此這篇關(guān)于SpringBoot接口獲取參數(shù)的常用注解詳解的文章就介紹到這了,更多相關(guān)SpringBoot接口獲取參數(shù)注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
package打包一個(gè)springcloud項(xiàng)目的某個(gè)微服務(wù)報(bào)錯(cuò)問題
這篇文章主要介紹了package打包一個(gè)springcloud項(xiàng)目的某個(gè)微服務(wù)報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
Spring Boot中使用Actuator的/info端點(diǎn)輸出Git版本信息
這篇文章主要介紹了Spring Boot中使用Actuator的/info端點(diǎn)輸出Git版本信息,需要的朋友可以參考下2017-06-06
大廠禁止SpringBoot在項(xiàng)目使用Tomcat容器原理解析
這篇文章主要為大家介紹了大廠禁止SpringBoot在項(xiàng)目使用Tomcat原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
springcloud?feign?接口指定接口服務(wù)ip方式
這篇文章主要介紹了springcloud?feign?接口指定接口服務(wù)ip方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
java簡單手寫版本實(shí)現(xiàn)時(shí)間輪算法
這篇文章主要為大家詳細(xì)介紹了java簡單手寫版本實(shí)現(xiàn)時(shí)間輪算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04
SpringBoot 集成 Statemachine的實(shí)戰(zhàn)指南
本文介紹了Spring State Machine框架的基本概念、核心特性、注解驅(qū)動(dòng)開發(fā)方式以及如何在Spring Boot項(xiàng)目中集成狀態(tài)機(jī),通過狀態(tài)機(jī),可以有效地管理復(fù)雜的狀態(tài)流轉(zhuǎn)邏輯,文章還討論了狀態(tài)機(jī)的持久化問題,并提供了一個(gè)自定義持久化實(shí)現(xiàn)的示例,感興趣的朋友跟隨小編一起看看吧2026-01-01
Mybatis關(guān)于動(dòng)態(tài)排序 #{} ${}問題
這篇文章主要介紹了Mybatis關(guān)于動(dòng)態(tài)排序 #{} ${}問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10

