无法使用Spring MVC和AJAX保存模型对象

时间:2016-07-09 22:32:49

标签: java jquery spring spring-mvc

这是我的控制者:

@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 个答案:

答案 0 :(得分:0)

尝试从客户端脚本发送application/json请求,并使用控制器中的@RequestBody来解析JSON请求。以下是这个想法:

在控制器中将@ModelAttribute更改为@RequestBody

@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody()
public Map<String,Object> save(@RequestBody Invoice invoice) throws IOException

更改客户端脚本以使用contentType: "application/json"JSON.stringify发送json请求:

var data = {
        amountDue: due,
        amountPaid: paid,
        items: [
        {
            productCode : "productCode",
            productName : "productName"
        }, 
        {
            productCode : "productCode",
            productName : "productName"
        }]};

$.ajax({
  url: '/product/save',
  dataType: 'json',
  contentType: "application/json",
  type: 'post',
  data: JSON.stringify(data),
  success: function(data, textStatus, jQxhr) { ... },
  error: function(jqXhr, textStatus, errorThrown) { .. }
});