springMVC中ajax和后台数据格式错误

 

前台ajax:

$.ajax("${pageContext.request.contextPath}/hello",// 发送请求的URL字符串。
{
dataType : "json", // 预期服务器返回的数据类型。如果服务器返回不一致,报 parseError
type : "post", // 请求方式 POST或GET
contentType:"application/json", // 发送信息至服务器时的内容编码类型,和 后台 consumes属性对应,这里指定的是"application/json"(当然可以不指定consumes属性,这里指定是为了过滤)
,如果指定后台consumes属性,其值必须也是"application/json",否则报错:unSupported Media Type
data:JSON.stringify({ price:123,name : "Spring MVC企业应用实战"}),// 发送到服务器的数据。如果

data的数据格式和contentType不一致,则报错:The request sent by the client was syntactically incorrect.
async: true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
// 请求成功后的回调函数。
success :function(data){
console.log(data);
},
// 请求出错时调用的函数
error:function(xhr,err,errObj){
console.log(err);
console.log(errObj);
alert("数据发送失败");
}
});

springMVC 后台:

@RequestMapping(value="/hello",method={RequestMethod.POST}, consumes="application/json")
public void hello(@RequestBody Product book){....}如果@RequestBody 注释的参数格式和前台传过来的(ajax的data属性值)格式不一致,报错:415 Unsupported Media Type

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

如果@RequestBody注释的参数是一个类,则前台传过来的(ajax的data属性值)数据如果是json格式(contentType:"application/json"),则会默认根据json属性名调用这个类的set方法,如果json属性名和这个类的set方法不一致,也不会报错

posted on 2017-12-26 15:19  吉晨  阅读(801)  评论(0编辑  收藏  举报

导航