@RequestParam和@RequestBody的区别

一、@RequestParam使用

使用@RequestParm用于绑定controller上的参数,可以是多个参数,也可以是一个Map集合,GET,POST均可

@PostMapping(value = "requestParam")
@ResponseBody
public Boolean requestParam(@RequestParam(name = "string",required = false) String str,@RequestParam(name = "integer",defaultValue = "123456") int integer){
    System.out.println("str:"+str);
    System.out.println("integer:"+integer);
    return true;
}

@RequestParm中name属性是指定参数名,required属性默认为ture,表示必传。若为false则为非必传。属性有defaultValue默认值选项,若该参数为null时,会将默认值填充到参数上。


image

@PostMapping(value = "paraMap")
@ResponseBody
public Map paraMap(@RequestParam Map<String, String> map){
    System.out.println("map name:"+map);
    return map;
}

还可以传入map集合
image


最后说一下使用@RequestParam的要求
- 均支持POST,GET请求
- 只支持Content-Type: 为 application/x-www-form-urlencoded编码的内容。Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)

二、@RequestBody

@RequestBody绑定一个对象实体

@PostMapping(value = "requestBody")
@ResponseBody
public User requestBody(@RequestBody  User user){
    System.out.println("user:"+user.getName());
    return user;
}

image
- 不支持get请求,因为get请求没有HttpEntity
- 必须要在请求头中申明content-Type(如application/json).springMvc通过HandlerAdapter配置的HttpMessageConverters解析httpEntity的数据,并绑定到相应的bean上
- 只能一个@RequestBody。且不能与@RequestParam一起使用

三、总结

区别 @RequestParam @RequestBody
content-type 仅支持x-www-form-urlencoded 支持json格式
请求类型 ALL 除了GET
注解个数 可多个 只能一个

猜你喜欢

转载自blog.csdn.net/Yoga0301/article/details/80640326