我收到一个错误:
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
属性不存在,因此会出现错误。