前后端分离模式中,参数的传递往往会涉及到@RequestBody注解、content-type请求方式、接收对象类型、请求参数格式等,稍有不慎便会出现一些意料之外的问题,故而鄙人做了一些测试和归纳,欢迎批评指正。
@RequestBody
1.@requestBody不处理content-type=application/x-www-form-urlcoded的请求,一般用来处理content-type=application/json的请求。
2.@RequestBody可以将请求体中的JSON字符串按照键名=属性名绑定到bean上,也可以JSONObject或者Map作为接收类型。
先将测试的bean贴出来:
public class RequestManager {
private String passNumber;
public String getPassNumber() {
return passNumber;
}
public void setPassNumber(String passNumber) {
this.passNumber = passNumber;
}
}
情景一
采用最普通的ajax请求,不做特殊处理:
$.ajax({
url: 'http://127.0.0.1:8085/im/user/test',
type: 'post',
data:{
"passNumber":"111111"
},
dataType:'json',
success: function (response) {
console.log("success");
},
error: function (r) {
console.log("error");
}
});
上述代码未声明content-type,ajax请求默认的content-type为application/x-www-form-urlcoded,而Spring的@RequestBody不处理content-type=application/x-www-form-urlcoded的请求,所以该种情景下,后台参数列表不允许使用@RequestBody注解,这里bean中的属性名要和前端JSON对象中的键名一致才能做映射。代码如下:
@RequestMapping(value="test",method=RequestMethod.POST)
public APIResult test(RequestManager manager){
log.info("test()请求入参:{}", JSON.toJSONString(manager));
return new APIResult(0,"SUCCESS");
}
若在参数列表前加@RequestBody注解,会抛如下异常:
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
除了用bean接收入参外,还可以直接用键名接收,用到@RequestParam注解,该注解的value和前端json数据中的键名一致,这样程序才能判定前端参数和后台参数列表的对应关系。如
@RequestMapping(value="test",method=RequestMethod.POST)
public APIResult test(@RequestParam("passNumber") String param){
log.info("test()请求入参:{}", param);
return new APIResult(0,"SUCCESS");
}
若后台的参数列表的参数名命名与前端JSON对象中的键名一致,则可以省略@RequestParam注解直接映射。同样的方法可以写成:
@RequestMapping(value="test",method=RequestMethod.POST)
public APIResult test(String passNumber){
log.info("test()请求入参:{}", passNumber);
return new APIResult(0,"SUCCESS");
}
情景二
ajax指定content-type=application/json
$.ajax({
url: 'http://127.0.0.1:8085/im/user/getCustListByManager',
type: 'post',
// 指定content-type
contentType: "application/json; charset=utf-8",
//修改data数据为字符串格式
data:
'{"passNumber":"111111"}'
,
dataType:'json',
success: function (response) {
console.log("success");
},
error: function (r) {
console.log("error");
}
});
上述代码中除了新增了content-type外,需要注意的是还将data的数据格式由json对象改成了字符串,这是因为@RequestBody处理的是json格式的字符串,无法直接解析json对象。若传json对象过去,会抛如下异常:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'passNumber': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'passNumber': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (PushbackInputStream); line: 1, column: 12]
在前端还可以用以下方法将json对象转为字符串:
JSON.stringify(jsonObj);
而此时后端接口参数列表必须加@RequestBody,否则无法解析前端json字符串,导致入参为空。另外bean中的属性名必须和前端JSON字符串中的键名一致,
@RequestMapping(value="test",method=RequestMethod.POST)
public APIResult test(@RequestBody RequestManager manager){
log.info("test()请求入参:{}", JSON.toJSONString(manager));
return new APIResult(0,"SUCCESS");
}
@RequestBody除了可以修饰bean类型,还可以修饰Map或者JSONObject类型,会直接将参数封装为Map或JSONObject。
@RequestMapping(value="test",method=RequestMethod.POST)
public APIResult test(@RequestBody JSONObject params){
log.info("test()请求入参:{}", JSON.toJSONString(params));
return new APIResult(0,"SUCCESS");
}
归纳
situational 1.
前端:
application/x-www-form-urlcoded + json对象
后端:
不允许加@RequestBody。
用bean接收。
用json键名接收,用@RequestParam指定前后台参数映射关系。
situational 2.
前端:
application/json + json字符串
后台:
需使用@RequestBody
用bean接收。
用JSONObject/Map接收
用字符串接收