[英]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.