java无法使用Spring MVC和AJAX保存模型对象
这是我的控制器:
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody()
public Map<String,Object> save(@ModelAttribute Invoice invoice) throws IOException {
Map<String, Object> data = new HashMap<String, Object>();
try {
productService.save(invoice);
data.put("message", "Ok");
} catch (Exception ex) {
data.put("message", ex.getMessage());
}
return data;
}
这是我的模型:
public class Invoice {
private Double amountPaid;
private Double amountDue;
private List<InvoiceItem> items;
public List<InvoiceItem> getItems() {
return items;
}
...
}
public class InvoiceItem {
private String productCode;
private String productName;
...
}
向控制器发送发票详细信息的jQuery代码:
var paid = jQuery("#amountPaid").val();
var due = jQuery("#amountDue").val();
var data = [{
productCode : "productCode",
productName : "productName"
}, {
productCode : "productCode",
productName : "productName"
}];
var r = confirm("Submit invoice?");
if (r == true) {
$.ajax({
url: '/product/save',
dataType: 'json',
type: 'post',
data: {
amountDue: due,
amountPaid: paid,
items: data
},
success: function(data, textStatus, jQxhr) { ... },
error: function(jqXhr, textStatus, errorThrown) { .. }
});
}
但是,在提交数据时,我会遇到以下错误:
org.springframework.beans.InvalidPropertyException: Invalid property 'items[0][productCode]' of bean class [Invoice]: Property referenced in indexed property path 'items[0][productCode]' is neither an array nor a List nor a Map; returned value was [productCode]]
# 1 楼答案
尝试从客户端脚本发送
application/json
请求,并在控制器中使用@RequestBody
来解析JSON请求。以下是想法:将控制器中的
@ModelAttribute
更改为@RequestBody
:并更改客户端脚本以发送带有
contentType: "application/json"
和JSON.stringify
的json请求: