我對Spring MVC有一個問題,如下所示:我使用JSR 303驗證以確保bean的屬性(請參閱PasswordInfo下面)既不爲空也不爲空。在使用JSR 303處理空值的Spring MVC控制器中驗證問題
我是還檢查業務邏輯規則,即兩個密碼相同。
問題是如果其中一個字符串字段(currentPassword和newPassword)爲空,它仍然被控制器傳遞給服務層以檢查業務邏輯規則,當然還會引發IllegalArgumentException!
這裏是PasswordInfo
豆:
@RooEquals
@RooJavaBean
public class PasswordInfo {
@NotNull(groups = { ValidationGroups.PasswordModification.class })
@NotEmpty(groups = { ValidationGroups.PasswordModification.class })
private String currentPassword;
@NotNull(groups = { ValidationGroups.PasswordModification.class, ValidationGroups.PasswordReset.class })
@NotEmpty(groups = { ValidationGroups.PasswordModification.class, ValidationGroups.PasswordReset.class })
@Size(min = 6, groups = { ValidationGroups.PasswordModification.class, ValidationGroups.PasswordReset.class })
private String newPassword;
...
下面是相關控制方法:
@RequestMapping(value = "/preference/password", method = RequestMethod.POST, produces = "text/html")
public String modifyPassword(@ModelAttribute @Validated({ ValidationGroups.PasswordModification.class }) PasswordInfo passwordInfo,
BindingResult bindingResult, Model model, @CurrentMember Member member) {
if (!preferenceService.passwordsMatch(member.getPassword(), passwordInfo.getCurrentPassword())) {
bindingResult.rejectValue("currentPassword", "controller.preference.wrong_current_password");
}
if (bindingResult.hasErrors()) {
model.addAttribute("passwordInfo", passwordInfo);
return "preference/password";
}
preferenceService.modifyPassword(member, passwordInfo.getNewPassword());
return "redirect:/preference/password";
}
下面是相關的服務層方法:
@Override
public boolean passwordsMatch(String encrypted, String plain) {
if (encrypted == null || encrypted.isEmpty() || plain == null || plain.isEmpty()) {
throw new IllegalArgumentException("One argument is null or empty");
}
return passwordEncoder.matches(plain, encrypted);
}
我的關注是要避免放置另一個綁定爲了避免重複自己
if (bindingResult.hasErrors()) {
model.addAttribute("passwordInfo", passwordInfo);
return "preference/password";
}
...業務邏輯校驗前...
任何人都可以請建議一個乾淨的解決了這個問題:Results.hasErrors阻止如?
哈代您好!實際上,這個問題與Spring MVC相比,更多地與JSR 303相關 - 儘管我在文章中添加了「bean-validation」標籤。基本上,我正在尋找一種乾淨的方式,以避免在自定義驗證與JSR 303驗證混合時重複'if(bindingResult.hasErrors())'塊。你看到了這個觀點嗎? – balteo