@RequestParam与@RequestBody使用对比

转载请注明出处:

  @RequestParam

    用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。

    (Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

  RequestParam可以接受简单类型的属性,也可以接受对象类型。
  实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。

  在Content-Type: application/x-www-form-urlencoded的请求中,
  get 方式中queryString的值,和post方式中 body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。
  

  代码示例:

    @GetMapping("/test-sentinel-resource")
    public String testSentinelResource(@RequestParam(required = false) String a) {
        if (StringUtils.isBlank(a)) {
            throw new IllegalArgumentException("a cannot be blank.");
        }
        return a;
    }

  当 required = false 时,a参数为可为空,当 required= true时,a参数不可为空。

@RequestBody

  一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。

  GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。

  POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来

    解析HttpEntity中的数据,然后绑定到相应的bean上。

  就application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的json数据传到后端,后端再进行解析。

  GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。

  POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用

  HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。

    @PostMapping("/create/user")
    public UserInfo createUser(@RequestBody CreateUserRequest request) {

        return userService.createUser(request);
    }

总结:

  1. form-data、x-www-form-urlencoded:不可以用@RequestBody;
  2. application/json:json字符串部分可以用@RequestBody;url中的?后面参数可以用@RequestParam
  3. get请求中不能用@RequestBody注解

  



原文地址:https://www.cnblogs.com/zjdxr-up/p/13227913.html