Spring Boot中请求参数读取方式
目录
一、前言
二、六种参数读取方式
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 接口设计与参数处理方面有所收获。如果你在开发过程中也有类似疑问,欢迎留言交流,共同进步