不使用@valid的Spring bean验证

时间:2012-10-17 02:58:03

标签: java spring spring-mvc bean-validation

我以传统的方式使用弹簧验证:

@RequestMapping(value="userRegistration", method = RequestMethod.POST)
public ModelAndView registerUser(@Valid UserAccountVO userAccountVO, BindingResult result,Model model){
    if (result.hasErrors()){
    // Do something
    }
//Do something else
}

效果很好。

但是现在我遇到了无法进行表单提交的情况,而是在javascript中获取值并使用Ajax点击按钮发送它们,就像这样。

var nameStr = $("#usrnmbx").val();
var emailidStr = $("#emailidbx").val()
//and more and then send them using ajax

因此,要实现bean验证,我的新方法看起来像这样。

@RequestMapping(value = "/userRegistration", method = RequestMethod.POST)
public @ResponseBody JSONresponse registerUser(HttpServletRequest request,@RequestParam(value = "name") String name, // and more){

UserAccountVO userAccountVO = new UserAccountVO(name, emailId,password, confirmPassword);
BindingResult result = new BeanPropertyBindingResult(userAccountVO,"userAccount");
userAccountValidator.validate(userAccountVO, result); //userAccountValidator is spring Validator implementation 
if (result.hasErrors()) {
 //Do something
}
//Do something else
}

但这看起来很脏。我绝对认为有更好的方法可以做到这一点。这似乎并不像我在POJO中提到的验证注释。 你们中的任何人都可以建议更好的实施。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用ajax提交整个表单。在这种情况下,您的命令对象应填充为普通表单提交。

这是我的方法

        function submitAjaxForm(form, url) {  
        $.post(url, $(form).serialize(),function(data) {
              ...........
            }); 
}