我有以下情況。我有一個驗證器來驗證我的命令對象,並將錯誤對象上的錯誤設置爲顯示在我的表單中。驗證程序按預期方式調用並且工作正常,但是由於驗證錯誤,我在錯誤對象中設置的錯誤不會顯示,因爲我發回到表單。未顯示彈簧驗證錯誤
驗證:
public void validate(Object obj, Errors err) {
MyCommand myCommand = (MyCommand) obj;
int index = 0;
for (Field field : myCommand.getFields()) {
if (field.isChecked()) {
if ((field.getValue() == null) || (field.getValue().equals(""))) {
err.rejectValue("fields[" + index + "].value", "errors.missing");
}
}
index++;
}
if (myCommand.getLimit() < 0) {
err.rejectValue("limit", "errors.invalid");
}
}
命令:
public class MyCommand {
private List<Field> fields;
private int limit;
//getters and setters
}
public class Field {
private boolean checked;
private String name;
private String value;
//getters and setters
}
形式:
<form:form id="myForm" method="POST" action="${url}" commandName="myCommand">
<c:forEach items="${myCommand.fields}" var="field" varStatus="status">
<form:checkbox path="fields[${status.index}].checked" value="${field.checked}" />
<c:out value="${field.name}" />
<form:input path="fields[${status.index}].value" />
<form:errors path="fields[${status.index}].value" cssClass="error" /></td>
<form:hidden path="fields[${status.index}].name" />
</c:forEach>
<fmt:message key="label.limit" />
<form:input path="limit" />
<form:errors path="limit" cssClass="error" />
</form:form>
控制器:
@RequestMapping(value = REQ_MAPPING, method = RequestMethod.POST)
public String onSubmit(Model model, MyCommand myCommand, BindingResult result) {
// validate
myCommandValidator.validate(myCommand, result);
if (result.hasErrors()) {
model.addAttribute("myCommand", myCommand);
return VIEW;
}
// form is okay, do stuff and redirect
}
難道我在驗證器和標籤中給出的路徑不正確?驗證器驗證包含對象列表的命令對象,所以這就是爲什麼當註冊錯誤消息(例如:「fields [」+ index +「]」.value)時,我在命令對象的列表中給出索引。 或者它是否包含錯誤的錯誤對象不可用於我的視圖?
任何幫助,歡迎和讚賞,它可能會給我一個暗示或指向我在正確的方向。
嘗試添加
在您的表單代碼中確保您的驗證器正常工作 – 2010-03-19 15:44:34