@requestbody接收json,必须一一对应吗

2022-03-18 科技 151阅读
jqajax通过postjson对象

遇到的HTTP415/400问题错误解决方案:
客户端:




Inserttitlehere
src="<%=basePath%>resources/scripts/jquery-2.0.3.min.js">

$(function(){
$("#send").click(function(){
varjsondata=$("#jsondata").val();
varjsonobj=JSON.parse(jsondata)

varcallback=function(data){
$("#result").html(JSON.stringify(data))
}

$.postJSON('<%=basePath%>api/user/test',jsonobj,callback)

});
})

$.postJSON=function(url,data,callback){
returnjQuery.ajax({
'type':'POST',
'url':url,
'contentType':'application/json',
'data':JSON.stringify(data),
'dataType':'json',
'success':callback
});
};



JSON对象



{"id":2,"gender":0,"mobile":"15072370640","password":"123456","accessToken":"fd6bf3dd3cca4b0ca7c9099447994dba"}



POST






springmvc服务端:

@RequestMapping(value="/test",method=RequestMethod.POST)
public@ResponseBodyMaptestPostJson(
@RequestBodyUserFormuserForm,
BindingResultbindingResult){

Mapmap=newHashMap();
if(bindingResult.hasErrors()){
map.put("errorCode","40001");
map.put("errorMsg",bindingResult.getFieldError().getDefaultMessage());
}

map.put("user",userForm);
returnmap;
}

测试:

结果

{"user":{"name":null,"id":2,"password":"123456","avatar":null,"gender":0,"mobile":"15072370640","accessToken":"fd6bf3dd3cca4b0ca7c9099447994dba"}}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com