SpringBoot MVC 接口传参总结

本文详细介绍了Spring MVC中不同方式的参数传递,包括URL路径变量、URL拼接参数、HttpServletRequest获取参数、@RequestParam注解、直接映射以及JavaBean接收参数。通过实例展示了GET和POST请求下的各种用法,包括form-data、x-www-form-urlencoded以及JSON格式的Body参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. URL 地址传参

请求形式:http://localhost:8080/get/url/10086

请求方法:GET POST

获取参数:

@RequestMapping(value = "url/{id}", method = {RequestMethod.GET, RequestMethod.POST})
public String testPathParam(@PathVariable("id") String id) {
    return "URL 传参 " + id;
}

2. URL 拼接参数

请求形式:http://localhost:8080/common/url?name=zhangsan&age=12

请求方法:GET POST

对应 Postman:

1. 从 HTTPRequest 请求体中获取参数

@RequestMapping(value = "url", method = {RequestMethod.GET, RequestMethod.POST})
public String testEmpty(HttpServletRequest request) {
    Map<String, String[]> paramMap = request.getParameterMap();
    return "URL 传参: name=" + request.getParameter("name") + ", age=" + request.getParameter("age");
}

2. @RequestParam,该方式参数不能为空

@RequestMapping(value = "param", method = {RequestMethod.GET, RequestMethod.POST})
public String testParam(@RequestParam("name") String name, @RequestParam Integer age) {
    return "URL 传参: name=" + name + ", age=" + age;
}

3. 直接映射,参数可以为空

@RequestMapping(value = "default", method = {RequestMethod.GET, RequestMethod.POST})
public String testDefault(String name, Integer age) {
    return "URL 传参: name=" + name + ", age=" + age;
}

4. Java Bean 接收参数,可以为空

@RequestMapping(value = "bean", method = {RequestMethod.GET, RequestMethod.POST})
public String testBean(NameAndAge nameAndAge) {
    return "URL 传参: name=" + nameAndAge.getName() + ", age=" + nameAndAge.getAge();
}

3. Form 表单形式传参

请求形式:http://localhost:8080/common/test

请求方法:GET POST

对应 Postman:

注意:

form-data:支持文件参数

x-www-form-urlencoded:只支持键值对,不支持 GET 请求方式,只支持 POST

用法基本与 2. URL 拼接参数 一致:

  1. 从 HTTPRequest 请求体中获取(x-www-form-urlencoded GET请求获取值为null)
  2. @RequestParam,该方式参数不能为空(x-www-form-urlencoded GET请求 400)
  3. 直接映射,参数可以为空(x-www-form-urlencoded GET请求获取值为null)
  4. Java Bean 接收参数,可以为空(x-www-form-urlencoded GET请求获取值为null)

4. Body 形式传参

这里以 application/json 为例

请求形式:http://localhost:8080/post/test

请求方法:POST

接收参数:@RequestBody

@RequestMapping(value = "body/bean", method = {RequestMethod.POST})
public String testBodyBean(@RequestBody NameAndAge nameAndAge) {
    return "Body 传参: name=" + nameAndAge.getName() + ", age=" + nameAndAge.getAge();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值