首页 > 解决方案 > ajax 将序列化的表单和模型列表发布到控制器方法

问题描述

我需要将视图表单、字符串列表和对象列表发布到控制器方法。

我的控制器方法看起来像这样

@ResponseBody
@RequestMapping(value = "/get-client-policies", method = RequestMethod.POST)
public ModelAndView getClientPolicies(@ModelAttribute("claimRegistrationForm") ClaimRegistrationForm claimRegistrationForm,
                                      @ModelAttribute("healthCardsList") List<String> healthCardsList,
                                      @ModelAttribute("bankAccountsList") List<CustomerBankAccounts> bankAccountsList,
                                      Map<String, Object> model) {

    return new ModelAndView("claims/reg/_form", model);
}

我的ajax调用:

$.ajax({
    type: 'POST',
    url: BASEHREF + 'ajax/claim-registration/get-client-policies,
    data: 'claimRegistrationForm=' + $('#claim_reg_form').serialize()
        + '&healthCardsList=' + $.parseJSON($('#healthCardsList').val())
        + '&bankAccountsList=' + $('#bankAccountsList').val(),
    success: function (response) {},
    error: function (jqXHR, error, errorThrown) {}
});

我的问题是如何发布bankAccountList参数。

BankAccountList 使用字符串化

@Override
public String toString() {
    return Pojomatic.toString(this);
}

并以表格形式存储在隐藏的输入字段中

<input type="hidden" id="bankAccountsList" th:value="${bank_accounts}" />

$('#bankAccountsList').val()的值为

"[CustomerBankAccount{bankCode: 1, bankAccountNo: 2, bankName: {name1}},
CustomerBankAccount{bankCode: 2, bankAccountNo: 3, bankName: {name2}}]"

在ajax发布之后我得到了

org.springframework.beans.BeanInstantiationException:无法实例化[java.util.List]:指定的类是一个接口

标签: javaajaxspring-mvcpost

解决方案


添加@RequestBody说明参数绑定到 HTTP 请求正文的注释。


推荐阅读