@RequestParam @RequestBody @PathVariable用法详解

  • Post author:
  • Post category:其他





@RequestParam @RequestBody @PathVariable用法详解

三个注解都是在我们进行请求时对服务端参数进行封装的,那么具体三个注解的使用,什么情况下,什么条件下使用呢?



一、@RequestParam

  1. @RequestParam接收的参数是来自于RequestHeader中,即请求头。

    @RequestParam用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容,Content-Type默认为该属性。且常用于Get请求其他请求也可使用;

    用处:(仅根据自己学习总结得出,若有不对请指出)在传递参数的情况下,不管参数是否必须传值的情况下皆可使用

    例如:


http://localhost:8080/test/?name=”xxx”

@GetMapping("/test")
  String test(@RequestParam("name") String name);
  • 值得注意的是不支持批量插入数据啊,如果改用 json 字符串来传值的话,类型设置为 application/json,点击发送的话,会报错,后台接收不到值,为 null。



二、@RequestBody

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);

比如:application/json、application/xml等类型的数据

且只能用于Post请求,Get方式没有请求体接收不到参数

    @PostMapping("/test2")
    String test2(@RequestBody Product product);



三、@PathVariable

@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值

一般也是用于Get请求,URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中

例如:

localhost:8080/id/1

    @GetMapping("id/{id}")
    public ObjectfindById(@PathVariable("id") long id) {
        return studentService.findById(id);
    }



四、@RequestParam与@RequestBody对比

两种注解使用多使用在伪Http客户端请求时对参数进行指定识别时使用,如OpenFeign在微服务之间参数调用时。

@RequestParam一般用来接收一个参数,比如单独的id或者name等参数,@RequestBody大多数用来对某个封装对象进行接收,从前端传来的数据封装成对象进行接收。

@RequestParam也是可以对数组对象进行封装的例如:

    @GetMapping("/test3")
    public String test3(@RequestParam("ids") String[] ids){
        for (String id : ids) {
            log.info("id:{}",id);
        }
        return "test3 ok端口"+port;
    }



版权声明:本文为weixin_53690059原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。