问题描述
先看有问题的代码:
controller:
@ResponseBody
@PostMapping(value = "/addUser")
public String addUser(@RequestBody AdminPersonVo adminPersonVo) {
return "success";
}
js:
$(form).ajaxSubmit({
url:"/addUser",
type:"POST",
contentType: 'application/json;charset=utf-8',
filtering: function(el, index) {
if ( !$(el).hasClass('ignore') ) {
return el;
}
},
success: function (data) {
alert(data);
}
});
表单提交报错如下:
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN
错误信息大概意思是: jackson 无法正确解析 json 。
开始踏上寻找解决之路……
看完上面代码能看出问题所在的话可以不用往下面看了;同时如果有其他解法欢迎留言
知识要点
要点一
ajax请求中的 contentType: ‘application/json;charset=utf-8’ 如果不加的话,会报如下错误:
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
表达意思也很清晰,默认的请求参数类型是: application/x-www-form-urlencoded;charset=UTF-8,而现在的代码不支持这种类型的参数请求。
要点二
聚焦 @RequestBody 这个注解。
@RequestBody 注解常用来处理 content-type 不是默认的 application/x-www-form-urlencoded 编码的内容,比如说:application/json 或者是 application/xml 等。
这就是为什么代码不支持 application/x-www-form-urlencoded 的原因。
解决办法
将 controller 中的 @RequestBody 去掉,将 JS 中的 contentType: ‘application/json;charset=utf-8’ 去掉,就能正常接收参数了
参考
- @requestBody 注解的使用:https://www.cnblogs.com/qiankun-site/p/5774300.html