一、@RequestParam使用
1:使用@RequestParm用于绑定controller上的参数,可以是多个参数,也可以是一个Map集合,GET,POST均可@RequestParm中name属性是指定参数名,required属性默认为ture,表示必传。若为false则为非必传。属性有defaultValue默认值选项,若该参数为null时,会将默认值填充到参数上。
2:
均支持POST,GET请求
只支持Content-Type: 为 application/x-www-form-urlencoded编码的内容。Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
二、@RequestBody
1:@RequestBody绑定一个对象实体 ,不支持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 |
注解个数 | 可多个 | 只能一个 |