gpt4 book ai didi

java - 不使用 @valid 的 Spring bean 验证

转载 作者:行者123 更新时间:2023-12-01 05:04:26 25 4
gpt4 key购买 nike

我以传统的方式使用了 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) {
...........
});
}

关于java - 不使用 @valid 的 Spring bean 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com