![](/img/trans.png)
[英]Why use @Valid in Spring MVC when HTML5 Validation exists
[英]Spring 3.1 Validation- How to use @ valid when you have 2 seperate models for form submission and persistence
我有兩個單獨的模型AccountDetailsForm
和AccountDetails
,前者用於表單提交,后者用於持久性。
AccountDetailsForm:
public class AccountDetailsForm {
private AccountDetails accountDetails;
@NotNull
private String confirmPassword;
//setter and getters
}
和AccountDetails:
@Entity
@Table(name = "ACCOUNT")
public class AccountDetails {
@Id
@Column(name = "USER_NAME")
@NotEmpty
@Max(value = 60)
private String userName;
@Column(name = "PASSWORD")
@NotEmpty
@Min(value = 8)
private String password;
//setters and getters
}
現在,我使用@Valid
驗證提交的表單:
@RequestMapping(value="userRegistration", method = RequestMethod.POST)
public ModelAndView registerUser(@Valid AccountDetailsForm accountDetailsForm, BindingResult result,Model model){
//I autowire localValidatorFactoryBean to validate the fields in AccountDetails bean.
localValidatorFactoryBean.validate(accountDetailsForm.getAccountDetails(), result);
if (result.hasErrors()){
model.addAttribute("accountDetailsForm", new AccountDetailsForm());
model.addAllAttributes(result.getModel());
return new ModelAndView("userRegistration");
}
我正在使用休眠進行持久化。 有沒有一種方法可以使用@Valid
來驗證accountDetails Bean,而不是顯式調用validate()
方法或使用Spring Validator實現?
我不介意聽到有關confirmPassword
解決方法的建議。 我正在遵循當前方法,因為在模型中沒有confirmPassoword
字段是沒有意義的。
把@Valid
在AccountDetails
的對象AccountDetailsForm
:
public class AccountDetailsForm {
@Valid
private AccountDetails accountDetails;
@NotNull
private String confirmPassword;
//setter and getters
}
當AccountDetailsForm
與驗證@Valid
在你的控制器, AccountDetails
也將被驗證。
參考示例在這里 。
查看批注內的groups字段:您可以指定要應用的依賴類。 在這里可能是這樣的:
@Valid(groups=AccountDetails.class)
使用Maven,我目前在Spring MVC 3.1項目上使用這些版本的庫:
springframework 3.1.2.RELEASE
javax.validation 1.0.0.GA
hibernate-validator-annotation-processor 4.1.0.Final
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.