使用Spring命令名处理错误

使用Spring命令名处理错误,spring,Spring,当使用Spring框架并在commandName对象上绑定表单以添加以下字段时 <form method="POST" action="addPerson.htm" commandName="person"> <input id="firstname" name="firstname"value="${person.firstname}"/> <br> <input id="nam

当使用Spring框架并在commandName对象上绑定表单以添加以下字段时

<form method="POST" action="addPerson.htm" commandName="person">
            <input id="firstname" name="firstname"value="${person.firstname}"/>
            <br>
             <input id="name" name="name" value="${person.name}"/>
             <br>
             <input id="age" name="age" value="${person.age}"/>
</form>

如何对此进行错误处理,例如,年龄必须是正数,firstname可以保留为空。

您需要创建一个新的验证程序类,实现
验证程序
接口。
您的验证器可以是这样的:

    public class PersonValidator implements Validator {
        public boolean supports(Class<?> clazz) {
            return Person.class.equals(clazz);
        }

        public void validate(Object target, Errors errors) {

            Person person=(Person)target;

            if ( person.getAge() < 0 ) {
                 errors.rejectValue("age", "age_positive");
                 // Or you can use this approach as well to parametrize the error message:
                //errors.rejectValue("age", "age_positive", ArrayParametersIfNeeded, "DefaultMessage");
            }

        }

    }
然后,在控制器方法中,您可以传递这个附加参数:
BindingResult
,如果需要,您将在那里获得错误信息。 此外,您需要将此位添加到表单中:

<form:errors path="age"/></c:set>

在您的

我建议您更改
标记的
元素

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(yourValidator);
    }
<form:errors path="age"/></c:set>