Spring MVC Bean验证 [英] Spring MVC Bean Validation
问题描述
我必须对使用Spring MVC 3的Web应用程序实施验证.问题是bean类具有诸如getProperty("name")和setProperty("name",valueObj)之类的方法.必须对通过将不同的值传递给getProperty("name")返回的数据进行验证,例如:getProperty("age")应当大于16,并且需要getProperty("state").
I have to implement validations for a web app that uses Spring MVC 3. The problem is that the bean class has methods like getProperty("name") and setProperty("name",valueObj). The validations have to be done on the data that is returned by passing different values to getProperty("name") , for eg: getProperty("age") should be greater than 16 and getProperty("state") should be required.
我想知道是否有验证这种Bean的支持,如果没有,可以解决什么问题.
I would like to know if there is any support for validation this kind of Bean and if not, what can be the work around.
谢谢, Atif
推荐答案
听起来像您想要一个实现org.springframework.validation.Validator
的自定义验证类.
It sounds like you want to a custom validation class which implements org.springframework.validation.Validator
.
@Component
public class MyValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return MyBean.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
MyBean myBean = (MyBean) target;
if (StringUtils.isBlank(myBean.getProperty("state"))) {
errors.rejectValue("state", "blank");
}
}
}
在您的控制器中,您将执行手动验证,如下所示:
In your controller you would do manual validaton like follows:
@Autowired
private MyValidator myValidator;
@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@ModelAttribute("myBean") MyBean myBean, BindingResult result) {
myValidator.validate(myBean, result);
if (result.hasErrors()) {
...
}
...
}
这篇关于Spring MVC Bean验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!