跳转至

多个参数接收总结

🔥 多个参数接收总结

1️⃣ 路径变量(PathVariable)

  • 用途:URL 路径里指定的单个或多个资源 ID。
  • 适合:单个 ID 或少量固定参数,不推荐批量操作。
  • 示例
1
2
3
4
5
6
7
8
9
@GetMapping("/students/{id}")
public Student getById(@PathVariable Integer id) { ... }

@DeleteMapping("/students/{ids}")
public void delete(@PathVariable String ids) {
    List<Integer> idList = Arrays.stream(ids.split(","))
                                 .map(Integer::valueOf)
                                 .toList();
}

2️⃣ 查询参数(RequestParam)

  • 用途:URL 查询字符串里传递参数,如分页、筛选、多值列表。
  • Spring 自动支持:List、数组、基本类型。
  • 示例
1
2
3
4
5
6
7
8
9
@GetMapping("/students")
public List<Student> list(
    @RequestParam Integer page,
    @RequestParam Integer pageSize,
    @RequestParam(required=false) String name,
    @RequestParam List<Integer> ids
) { ... }

// URL: /students?page=1&pageSize=10&name=Tom&ids=1&ids=2&ids=3

3️⃣ 请求体 JSON(RequestBody)

  • 用途:前端 POST/PUT 传复杂对象、数组或批量数据。
  • 适合:新增、更新、批量操作,参数复杂。
  • 示例
1
2
3
4
5
@PostMapping("/students")
public void add(@RequestBody Student student) { ... }

@DeleteMapping("/students")
public void delete(@RequestBody List<Integer> ids) { ... }

4️⃣ 表单参数(Form / x-www-form-urlencoded)

  • 用途:传统表单提交。
  • Spring 支持:直接绑定到对象或字段。
  • 示例
1
2
3
@PostMapping("/students")
public void add(Student student) { ... }
// 表单提交: name=Tom&age=18&gender=1

5️⃣ 请求头(RequestHeader)

  • 用途:获取 HTTP Header 的参数,如 Token、版本号。
  • 示例
@GetMapping("/profile")
public User profile(@RequestHeader("Authorization") String token) { ... }

6️⃣ Cookie(CookieValue)

  • 用途:获取 Cookie 值,如登录态。
  • 示例
@GetMapping("/profile")
public User profile(@CookieValue("SESSIONID") String sessionId) { ... }

7️⃣ 综合示例

1
2
3
4
5
6
7
@PostMapping("/students")
public void add(
    @RequestParam Integer classId,            // 查询参数
    @RequestBody List<Student> students,      // 请求体 JSON 批量学生
    @RequestHeader("Authorization") String token, // 请求头
    @CookieValue("SESSIONID") String sessionId   // Cookie
) { ... }

📌 总结对比表

参数来源 注解 典型场景 支持类型
路径变量 @PathVariable 单个 ID,少量固定参数 String, Integer, Long
查询参数 @RequestParam 分页、多条件查询、List String, Integer, List, 数组
请求体 JSON @RequestBody 批量操作、复杂对象 对象、List、Map、数组
表单参数 无注解 /@ModelAttribute 前端表单提交 对象、基本类型
请求头 @RequestHeader Token、版本号 String、基本类型
Cookie @CookieValue 登录态 String、基本类型

💡 原则

  1. 单个资源 → @PathVariable
  2. 多条件或可选参数 → @RequestParam
  3. 批量或复杂对象 → @RequestBody
  4. Token、会话信息 → @RequestHeader / @CookieValue