@requestBody 与@requestparam详解

  • @RequestParam注解接收的参数是来自于requestHeader中,即请求头。都是用来获取请求路径url 中的动态参数,格式为xxx?username=123&password=456。功能与@pathvarible类似。

@RequestParam(value="字段名称",required=true/false,defaultValue=""),当字段非必填时,一般要传默认值。

@RequestMapping("/list")
public String test(int userId) {
  return "list";
 
}
 
@RequestMapping("/list")
public String test(@RequestParam int userId) {
  return "list";
}

第一种写法参数为非必传,第二种写法参数为必传。参数名为userId。(@RequestBody同理)

第二种写法可以通过@RequestParam(required = false)设置为非必传。因为required值默认是true,所以默认必传。(@RequestBody同理)

第二种写法可以通过@RequestParam("userId")或者@RequestParam(value = "userId")指定参数名。

第二种写法可以通过@RequestParam(defaultValue = "0")指定参数默认值。

如果参数是对象,但传的值(http请求Header中)为对象里的一个字段(基本数据类型),则不能加@RequestParam,否则就用对象名去接收参数了,会接收不到参数(required=false)或报错

  • RequestBody注解接收的参数则是来自于requestBody中,即请求体中。
  1. Content-Type,内容类型,一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,这就是经常看到一些Asp网页点击的结果却是下载到的一个文件或一张图片的原因。
  2. 使用与不使用@RequestBody:

(1) 必须使用@requestBody.当请求content_type为:application/json类型的请求,数据类型为json时, json格式如下:{"aaa":"111","bbb":"222"}

(2) 可不使用@requestBody.当请求content_type为:application/x-www-form-urlencoded类型的或multipart/form-data时,数据格式为aaa=111&bbb=222。post请求一般用json格式,通过@RequestBody(required=true/false)标注。

  • Spring初始化问题:
  1. 无论加了@RequestParam(required=false)还是@RequestBody(required=false),传空的情况下controller中的参数均为null,不会赋默认值。
  2. 若不加@RequestBody或@RequestParam,对象参数会被当作行参初始化一个。但对象里的参数为null或默认值(设定了默认值)。(String、包装类初始化为null,基本数据类型会报错,因为无法为基本数据类型赋值null)

 

参考:

https://blog.csdn.net/u011410529/article/details/66974974

https://blog.csdn.net/qq_26761587/article/details/73691189

https://blog.csdn.net/jiashanshan521/article/details/88244735?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

https://blog.csdn.net/u013805360/article/details/79527175?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

 

posted @ 2020-08-18 11:53  机械公敌  阅读(2712)  评论(0编辑  收藏  举报