最近在做第一个基于Spring MVC的项目,发现了一些在学习过程中没有注意到的问题,比如数据绑定,Json数据转换等等。。。
数据绑定
数据绑定最主要的问题就是复杂对象数组的绑定,当然,如果真在后台通过数组来绑定前台传递过来的Json字符串,会出很多问题,比如java.util.LinkedHashMap cannot be cast to com.xxx,要正确处理这个错误,真的会让人崩溃的。所以,我干脆在后台通过String来接收前台传过来的Json字符串,再对String进行处理,并且还有一点必须注意的是,不能设置contentType:”application/json”。具体看如下的代码注释:
var mails = new Array ();
$.each(rows, function (i, n) {
mails.push({"mail" : n.mail, "studentID" : n.studentID, "courseID" : courseID});
});
$.ajax({
url : "course/send" ,
type : "post" ,
data : JSON .stringify(mails),
dataType : "json" ,
success : function (data) {
$.messager.alert('提示' , data.mes, 'info' );
},
error : function (data) {
$.messager.alert('提示' , "发送失败" , 'info' );
}
});
@RequestMapping(value = "/send" , method = RequestMethod. POST)
@ResponseBody
public Map < String , String > send(@RequestBody String mails) throws Exception {
Map < String , String > map = new HashMap< String , String > ();
JSONArray json = JSONArray. fromObject(mails);
List < SendModel> models = (List < SendModel> ) JSONArray. toCollection(json,SendModel. class);
for(SendModel model : models){
System. out. println(model);
}
map . put("mes" , "发送成功" );
return map ;
}
需要指定content:”application/json”的情况 正如前面所说的复杂对象数组的绑定如果在后台通过对应的对象数组来接受各种转换太麻烦了,所以在这里举例的是String数组的绑定,如果在后台通过String[]来接收就必须指定content:”application/json“(当然,在后台通过String先接受Json字符串是不用指定的),否则会出现415 Unsupported Media Type错误提示。Demo如下:
var test = new Array ();
test.push("aaa" );
test.push("bbb" );
test.push("ccc" );
alert(test);
$.ajax({
url : "course/send" ,
type : "post" ,
data : JSON .stringify(test),
dataType : "json" ,
contentType : "application/json" ,
success : function (data) {
$.messager.alert('提示' , data.mes, 'info' );
},
error : function (data) {
$.messager.alert('提示' , "发送失败" , 'info' );
}
});
@RequestMapping (value = "/send" , method = RequestMethod.POST)
@ResponseBody
public Map<String, String> send (@RequestBody String[] test) throws Exception {
for (String t : test){
System.out.println(t);
}