@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时,会将默认值填充到参数上。


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

还可以传入map集合


最后说一下使用@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;
}
  • 不支持get请求,因为get请求没有HttpEntity
  • 必须要在请求头中申明content-Type(如application/json).springMvc通过HandlerAdapter配置的HttpMessageConverters解析httpEntity的数据,并绑定到相应的bean上
  • 只能一个@RequestBody。
  • 可以与@RequestParam一起使用,但建议最好不要与@RequestParam一起使用,是因为@RequestBody会将InputStream吃掉,造成后面的@RequsetParam无法匹配到参数而报400

三、总结

区别@RequestParam@RequestBody
content-type仅支持x-www-form-urlencoded支持json格式
请求类型ALL除了GET
注解个数可多个只能一个
  • 2
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值