繁体   English   中英

不使用@valid的Spring bean验证

[英]Spring bean validation without using @valid

我已经以这种常规方式使用了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
}

那很好,很好。

但是现在我遇到了这样的情况:我无法进行表单提交,而是在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中放置的验证注释。 你们中谁能建议一个更好的实现。 提前致谢。

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

这是我的方法

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

暂无
暂无

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

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