有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    尝试从客户端脚本发送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) { .. }
    });