问题描述
先看有问题的代码:
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’ 去掉,就能正常接收参数了
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论