[英]Spring validation errors not displayed
我有以下情况。 我有一个验证器来验证我的命令对象,并设置Errors对象上的错误,以便在我的表单中显示。 验证器按预期调用并且工作正常,但是当我因验证错误而被发送回我的表单时,我不会显示我在Errors对象上设置的错误。
验证器:
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)。 或者是否包含错误的Errors对象不可用于我的视图?
欢迎和赞赏任何帮助,它可能会给我一个提示或指出我正确的方向。
我发现你的问题是什么。 对象myCommand
属性fields
始终为null。 您需要创建类mycommand的构造函数中,你需要使用LazyList
从Apache的共享或AutoPopulatingList
从Spring构建的汽车越来越多的Field
在示例中(使用AutoPopulatingList):
public class MyCommand {
private List<Field> fields;
private int limit;
//getters and setters
//...
//Constructor
public MyCommand() {
fields = new AutoPopulatingList<Field>(Field.class);
}
}
行err.rejectValue("fields[" + index + "].value", "errors.missing");
不会做你想要达到的目标。 第一个参数必须是Command bean的属性名称,在您的case字段中。
要向用户发送消息,您必须在属性文件中使用可参数化的消息,例如。 myform.field.error = you have an error in field {0}
所以,使用Errors对象的这个方法:
void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage)
将index
传递给errorArgs的位置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.