当前位置:   article > 正文

【详细】Spring Boot项目中rest接口定义与参数传递和接收_restclient form-data

restclient form-data

建议使用rest Client测试接口

方式一:form-data形式

参数以key-value形式传递,参数和值会直接拼接到请求url后边显示存在(POST http://localhost:8080/users/insert?id=5&userName=刘明);
适用于所有请求方式;
后台接收参数时使用注解@RequestParam

POST

提交资源时一般post请求方式,当然所有的增删改也可已使用post请求
使用@RequestParam(value = “key”) 绑定请求参数到方法入参时,参数名可以不与前台key一致

@RestController
@RequestMapping("/users")
public class UsersController {
    @PostMapping("/insert")
    public RestResult insertUserInfo(@RequestParam("userId") int id, String userName, String passWord, int age,String sex, String phone) {...}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

请求参数可以这样显示接收,也可以从 request 中获取

insertUserInfo(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        String phone = request.getParameter("phone");
		...
}
  • 1
  • 2
  • 3
  • 4
  • 5

在这里插入图片描述
如果请求参数为定义的对象属性时,可以直接使用对象接收参数

public class User {
    private int id;
    private String userName;
    private String passWord;
    private int age;
    private String sex;
    private String phone;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
@PostMapping("/insert")
    public RestResult insertUserInfo(User user) {...}
  • 1
  • 2
DELETE

删除资源
使用@PathVariable 获取url路径中的参数

@DeleteMapping("/delete/{id}")
public RestResult deleteUser(@PathVariable("id") int userId) {...}
  • 1
  • 2
PUT

更新资源

@PutMapping("/update/{id}")
public RestResult updateUser(@PathVariable int id, String phone)...
  • 1
  • 2

在这里插入图片描述

GET

获取资源

@GetMapping("/query/{id}")
    public RestResult queryUser(@PathVariable int id) {...}
  • 1
  • 2

在这里插入图片描述

方式二、content-type形式

因为GET请求头中无content-type字段,所以此种方式只适用于POST/DELETE/PUT请求,用来处理:applicatin/json格式的参数
参数以json形式传递,后台获取参数时使用注解@RequestBody

@PostMapping("/insert")
    public RestResult insertUserInfo(@RequestBody User user) {...}
  • 1
  • 2

在这里插入图片描述
我们也可以使用@JsonProperty 注解来绑定Json中的key和Bean实体的属性
这时候,前台在传递参数时,可以使用与属性名一致,也可以与注解中的value一致
但是这里得注意:这里返回给前台的json对象中的key将会是直接中的值

public class User {
    private Integer id;
    @JsonProperty("name")
    private String userName;
    @JsonProperty("pass")
    private String passWord;
    private Integer age;
    private String sex;
    private String phone;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在这里插入图片描述

总结

很明显,方式一在传递参数时,如果传入的参数太长时,或许会超过某些浏览器与服务器对URL的长度限制,会导致请求失败,因此在实际应用中,对于GET请求我们一般使用form表单形式传递参数,POST/DELETE/PUT请求我们考虑使用方式二;
对于请求参数过多的,我们可以使用Java Bean来接收参数

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/869804
推荐阅读
相关标签
  

闽ICP备14008679号