Spring MVC Bean Validation

强颜欢笑 提交于 2019-12-11 19:16:33

问题


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.

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.

Thanks, Atif


回答1:


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()) {
        ...
    }

    ...

}



回答2:


I don't think so. Bean validation is performed on javabeans, i.e. class fields with getters and setters. Even if you can register a custom validator, and make validation work, binding won't work. You would need to also register a custom binder that populates your object. It becomes rather complicated. So stick to the javabeans convention.



来源:https://stackoverflow.com/questions/10288698/spring-mvc-bean-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!