@RequestParam接收JSON的字符串,它和@RequestBody的区别
首先@RequestParam
1. 用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型) @RequestParam可以接受简单类型的属性,也可以接受对象类型。 2. 用来处理 multipart/form-data (表单上传的)
那么 如何使用@RequestParam 接受JSON的
前端代码
const message = {
"data": {
"userInfo": "2804951212",
"offerId": offerId,
"action": "distribution",
"categoryNav": categoryNav
},
"gmtBorn": time,
"msgId": time,
"type": "PRODUCT_COLLECTION",
"userInfo": "chrome"
};
$.ajax({
contentType :application/x-www-form-urlencoded,
type:post,
url: baseUrl+/ali-receive,
data:"message="+JSON.stringify(message)
});
后端代码
@PostMapping("/ali-receive")
public void aliReceive(@RequestParam("message") String message) {
ReceiveLog receiveLog = JSON.parseObject(message, ReceiveLog.class);
}
@RequestBody
注解@RequestBody接收的参数是来自requestBody中,即请求体。一般用于处理非 Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。
就application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的json数据传到后端,后端再进行解析。
GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用
HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。
从content-type方面总结
① form-data、x-www-form-urlencoded:不可以用@RequestBody;可以用@RequestParam。
② application/json:json字符串部分可以用@RequestBody;url中的?后面参数可以用@RequestParam。
