Axios 传参与 Spring Boot 接收参数完全指南


Axios 传参与 Spring Boot 接收参数完全指南

本文详细说明前端 Axios 传参与后端 Spring Boot 接收参数的各类场景,包括 GET/POST/PUT/DELETE 请求、路径参数/查询参数/请求体参数 的传递方式,以及如何接收 ListMap 等复杂类型。通过代码示例和对比表格,帮助开发者快速掌握正确用法。


一、GET 请求

1.1 查询参数(URL 参数)

Axios 传参

使用 params 字段,参数自动拼接到 URL:

axios.get('/api/user', {
  params: {
    id: 1,
    name: 'John'
  }
});
// URL 结果:/api/user?id=1&name=John
Spring Boot 接收
  • 使用 @RequestParam 注解(可省略参数名匹配时):
    @GetMapping("/api/user")
    public String getUser(
        @RequestParam Long id,        // 显式注解
        String name                   // 省略注解(参数名需一致)
    ) {
        // 业务逻辑
    }
    

1.2 路径参数

Axios 传参

参数直接嵌入 URL:

axios.get(`/api/user/${userId}`);
Spring Boot 接收

使用 @PathVariable 注解:

@GetMapping("/api/user/{userId}")
public String getUser(@PathVariable Long userId) {
    // 业务逻辑
}

1.3 接收 ListMap

Axios 传参(List)

需序列化为重复参数:

axios.get('/api/users', {
  params: { ids: [1, 2, 3] },
  paramsSerializer: params => qs.stringify(params, { arrayFormat: 'repeat' })
});
// URL 结果:/api/users?ids=1&ids=2&ids=3
Spring Boot 接收
@GetMapping("/api/users")
public List<User> getUsers(@RequestParam List<Long> ids) { ... }

@GetMapping("/api/user")
public Map<String, String> getParams(@RequestParam Map<String, String> params) { ... }

二、POST 请求

2.1 JSON 数据(默认)

Axios 传参

使用 data 字段,默认 Content-Type: application/json

axios.post('/api/user', { 
  name: 'John', 
  address: { city: 'New York' } // 嵌套对象
});
Spring Boot 接收

使用 @RequestBody 绑定对象:

@PostMapping("/api/user")
public User createUser(@RequestBody User user) { ... }

2.2 表单数据(Form Data)

Axios 传参

需设置 Content-Type: application/x-www-form-urlencoded

const params = new URLSearchParams();
params.append('name', 'John');
params.append('age', 30);

axios.post('/api/user', params, {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Spring Boot 接收
  • 逐个接收或绑定到对象:
    @PostMapping("/api/user")
    public String createUser(
        @RequestParam String name,    // 逐个接收
        @ModelAttribute User user     // 绑定到对象(可省略注解)
    ) { ... }
    

2.3 接收 ListMap

Axios 传参(List)

发送 JSON 数组:

axios.post('/api/users', [
  { name: 'John' }, { name: 'Alice' }
]);
Spring Boot 接收
@PostMapping("/api/users")
public String createUsers(@RequestBody List<User> users) { ... }
Axios 传参(Map)

发送 JSON 数组:

axios.post('/api/data', {
  key1: 'value1',
  key2: { nestedKey: 'nestedValue' }
});
Spring Boot 接收
@PostMapping("/api/data")
public String handleData(@RequestBody Map<String, Object> data) { ... }

三、PUT/DELETE 请求

3.1 更新资源(PUT)

Axios 传参

混合路径参数和请求体:

axios.put(`/api/user/${userId}?role=admin`, { name: 'Alice' });
Spring Boot 接收
@PutMapping("/api/user/{id}")
public User updateUser(
    @PathVariable Long id,
    @RequestParam String role,
    @RequestBody User user
) { ... }

3.2 删除资源(DELETE)

Axios 传参

路径参数 + 查询参数:

axios.delete(`/api/user/${userId}?force=true`);
Spring Boot 接收
@DeleteMapping("/api/user/{id}")
public void deleteUser(
    @PathVariable Long id,
    @RequestParam boolean force
) { ... }

四、注解使用规则

4.1 @RequestParam@PathVariable

注解必须显式使用?适用场景
@RequestParam参数名不一致时需显式URL 查询参数或表单字段
@PathVariable必须显式使用URL 路径参数(如 /user/{id}

4.2 @RequestBody@ModelAttribute

注解数据来源Content-Type绑定机制
@RequestBody请求体(JSON/XML)application/json反序列化为对象
@ModelAttributeURL 参数或表单字段application/x-www-form-urlencoded按名称匹配到对象属性

五、常见问题解答

5.1 参数未正确接收?

  • 检查点
    1. 前端 Content-Type 是否与后端匹配(如 JSON 需 @RequestBody)。
    2. 参数名是否一致(尤其是 @RequestParam@PathVariable)。
    3. GET 请求是否误用请求体(默认不支持)。

5.2 日期/时间参数处理

在字段上添加 @DateTimeFormat

public class User {
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private LocalDate birthday;
}

5.3 接收 Map 的注意事项

  • GET 请求Map 的值为 String 类型。
  • POST 请求Map 可嵌套复杂对象(需 @RequestBody)。

六、总结速查表

场景HTTP 方法Axios 传参方式Spring Boot 接收方式
查询用户GETparams@RequestParam / 无注解
创建用户(JSON)POSTdata 对象@RequestBody
提交表单POSTFormData@RequestParam / @ModelAttribute
更新用户PUT路径参数 + JSON 请求体@PathVariable + @RequestBody
批量删除用户DELETE路径参数 + 查询参数@PathVariable + @RequestParam

通过本文档,您可快速掌握前后端参数传递的核心规则。建议结合代码示例和对比表格,根据实际场景选择正确的传参方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值