简体   繁体   English

不使用@valid的Spring bean验证

[英]Spring bean validation without using @valid

I have used spring validation in the conventional way like this: 我已经以这种常规方式使用了spring验证:

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

That works well and good. 那很好,很好。

But now I have case where I can't do a form submission, but instead get values in javascript and send them using Ajax on click of a button, something like this. 但是现在我遇到了这样的情况:我无法进行表单提交,而是在javascript中获取值,然后在单击按钮时使用Ajax发送它们,类似这样。

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

So to implement bean validation my new method looks something like this. 因此,为了实现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
}

But this looks dirty. 但这看起来很脏。 I definitely think there are better ways of doing this. 我绝对认为有更好的方法可以做到这一点。 And this doesn't seem like picking up the validation annotations that I have put up in the POJO. 而且这似乎不像我在POJO中放置的验证注释。 Can any of you suggest a better implementation. 你们中谁能建议一个更好的实现。 Thanks in advance. 提前致谢。

you can submit whole form with ajax. 您可以使用ajax提交整个表单。 In this case your command object should be populated as ordinary form submission. 在这种情况下,您的命令对象应填充为普通表单提交。

here is my aproach 这是我的方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM