我收到一个错误:

Invalid property 'redeemVoucherForm' of bean class [my.testapp.forms.RedeemVoucherForm]: Bean property 'redeemVoucherForm' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?


RedeemVoucherForm.java:

package my.testapp.forms;

public class RedeemVoucherForm {

    private String voucherCode;

    public String getVoucherCode() {
        return voucherCode;
    }

    public void setVoucherCode(String voucherCode) {
        this.voucherCode = voucherCode;
    }
}


在我的PageController.java中,我在调用方法model.containsAttribute(“ redeemVoucherForm”)时添加模型redeemVoucherForm

@RequestMapping(method = RequestMethod.GET)
public String showPage(final Model model) {
    ...
    model.addAttribute("redeemVoucherForm", new RedeemVoucherForm());
    ...
    return REDIRECT_PAGE_URL;
}

@RequestMapping(value = "/redeem-voucher", method = RequestMethod.POST)
public String redeemVoucher(@Valid final RedeemVoucherForm redeemVoucherForm, final BindingResult bindingResult, final RedirectAttributes redirectModel, final Model model, HttpServletRequest request) {
    LOG.debug("<POST> Redeeming voucher...");

    return REDIRECT_PAGE_URL;
}


pageDisplay.jsp:

<c:url value="/page/redeem-voucher" var="redeemVoucherAction" />
<form:form action="${redeemVoucherAction}" method="post" commandName="redeemVoucherForm">
        <form:input cssClass="form-control" type="text" path="redeemVoucherForm.voucherCode"/>
        <button type="submit" class="btn btn-primary btn-block checkoutButton">
            <spring:theme text="Redeem Voucher"/>
        </button>
</form:form>


设置模型redeemVoucherForm后,我还能缺少什么?

最佳答案

我相信这条线

    <form:input cssClass="form-control" type="text" path="redeemVoucherForm.voucherCode"/>


应该

    <form:input cssClass="form-control" type="text" path="voucherCode"/>


path<form:input>元素应相对于已设置为commandName<form:form>的对象。在您的情况下,此对象是类RedeemVoucherForm的实例。

如果将路径设置为redeemVoucherForm.voucherCode,Spring将在类redeemVoucherForm上查找RedeemVoucherForm属性。它期望此值是具有voucherCode属性的某个对象,从中可以读取表单值。当然,redeemVoucherForm属性不存在,因此会出现错误。

10-05 21:29