一、现象
由于项目是前后端分离,因此后台使用的是spring boot,做成微服务,只暴露接口。接口设计风格为restful的风格,在get请求下,后台接收参数的注解为RequestBody时会报错;在post请求下,后台接收参数的注解为RequestParam时也会报错。
二、原因
@RequestParam
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
RequestParam可以接受简单类型的属性,也可以接受对象类型。 例如
public R getCompletedInfo(@RequestParam Map<String, Object> params) public R getCompletedInfo(@RequestParam AuditDecisionEntity auditDecisionEntity) public R getCompletedInfo(@RequestParam String id)
都可以获取到数据。
实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。
注意:
在Content-Type: application/x-www-form-urlencoded
的请求中,
get 方式中queryString的值,和post方式中 body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到
@RequestBody
处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded
编码格式的数据。
- GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
- POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型
Content-Type
,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。
三、总结
- 在GET请求中,不能使用@RequestBody。
- 在POST请求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,对于参数转化的配置必须统一。另贴上例子:
get请求
前台:
$.getJSON(serverPath + "project/engineering/completedcheck/",{"gongchengid":GetUrlParam("id")}, function (result) {
后台:
@RequestMapping("/completedcheck") public R completedcheck(@RequestParam Map<String, Object> params){
post请求
前台:
$.post(serverPath + 'project/engineering/updateData', JSON.stringify({"id":GetUrlParam("id"),"gongchengztxsz":"基本信息"}), function (result) {
后台:
@RequestMapping("/updateData") public R updateData(@RequestBody EngineeringEntity engineering){