SpringMV常用注解之@requestbody和@requestparam

基本介绍

  • @requestparam

属性介绍

  1. required:表示是否必须,默认为 true,必须
  2. defaultValue:可设置请求参数的默认值
  3. value:为接收url的参数名(相当于key值)
  • @requestbody

属性介绍

  1. required:表示是否必须,默认为 true,必须

使用方式

@requestparam

@requestbody

  注解@RequestBody接收的参数是来自requestBody中,即请求体。一般用于处理非 Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。就application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的json数据传到后端,后端再进行解析

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

  POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。

注意:前端使用$.ajax的话,一定要指定 contentType: "application/json;charset=utf-8;",默认为 application/x-www-form-urlencoded

    @PostMapping("test4")
    @ResponseBody
    public String test4(@RequestBody List<UserEntity> lists) {
        return "用户:" + JSONUtil.toJsonStr(lists);
    }

    @PostMapping("test5")
    @ResponseBody
    public String test5(@RequestBody List<Map<String, Object>> maps) {
        return "用户:" + JSONUtil.toJsonStr(maps);
    }

通过postman正确调用:

 如果使用form表单提交,就会报错:

 

  get请求:

  1. 直接获取request    如: public String getHtml(HttpServletRequest request) {}
  2. 什么也不加,直接在方法中获取参数值   如: public String getHtml(String url, String token) {}
  3. 利用@RequestParam    如: public User getUserInfo(@RequestParam(value = "url",required = false) String url){}

  post请求:

  1. 直接获取request    如: public String getHtml(HttpServletRequest request) {}
  2. 使用@RequestBody 可接受的参数 String, Map,JSONObject,或者对应的JavaBean,如: public User getUserInfo(@RequestBody Map<String,String> map){}
  3. 直接获取request    如: public String getHtml(HttpServletRequest request) {}

区别  

 

  用来处理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可以获取的到,除此之外delete类型的请求也可以使用@RequestParam注解。

  属性介绍:

  1. required:表示是否必须,默认为 true,必须
  2. defaultValue:可设置请求参数的默认值
  3. value:为接收url的参数名(相当于key值)

@requestbody

   处理HttpEntity传递过来的数据,也就是注解@RequestBody接收的参数是来自requestBody中,即请求体。一般用来处理Content-Type不为application/x-www-form-urlencoded编码格式的数据。

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

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

    required:表示是否必须,默认为 true,必须
  • 区别
  1. 在GET请求中,不能使用@RequestBody。
  2. 在POST请求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,对于参数转化的配置必须统一。
  3. 使用@RequestBody接受的参数是不会被Servlet转化统一放在request对象的Param参数集中,@RequestParam是可以的。

  @RequestBody和@RequestParam的区别

  @RequestBody和@RequestParam的请求方式get和post关系

猜你喜欢

转载自www.cnblogs.com/htyj/p/13365476.html
今日推荐