0
我们在我们的web应用程序中使用Spring MVC 3.0。我们也在使用Spring MVC的验证框架。在Spring MVC中验证
在进行验证时,我们需要为我们需要验证的每个实体创建验证器。例如,如果我有一个Person实体,我将使用下面的PersonValidator来验证它。
public class PersonValidator implements Validator {
/**
* This Validator validates just Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "field.required");
}
}
我的问题是,是否有可能对不同方法的相同实体有不同的验证。
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid Person person, BindingResult result) {
if (result.hasErrors()) {
return "person/new";
}
personService.addPerson(person);
return "redirect:/persons";
}
@RequestMapping(method = RequestMethod.POST)
public String update(@Valid Person person, BindingResult result) {
if (result.hasErrors()) {
return "person/edit";
}
personService.updatePerson(person);
return "redirect:/persons";
}
我想验证名字,姓氏和年龄,同时添加一个新的人,但在更新时我不希望年龄是强制性的。
这只是一个随机的情况,它可以是任何实体和任何属性。
我们该如何处理这种情况?
谢谢。
以前没有人做过这个吗?有任何想法吗 ? – ashishjmeshram 2011-04-29 13:56:37