为什么我必须在Spring中使用@Valid
注释,即使我创建了如下实体:
public class MyEntity{
private Long id;
@NotNull
@Size(min=5, max=16)
private String username;
@NotNull
@Size(min=5, max=25)
private String password;
@NotNull
@Size(min=2, max=30)
private String firstName;
@NotNull
@Size(min=2, max=30)
private String lastName;
@NotNull
@Email
private String email;
.......
}
在EJB中,我可以创建一个带注释的实体类,它会自动在Web应用程序中强制执行验证约束。但是为什么Spring MVC需要这个@Valid
额外的注释?
答案 0 :(得分:0)
@valid不是一个额外的注释,它在表单绑定时非常有用, 例如,如果您有一个创建MyEntity的表单
<form modelAttribute="MyEntity">
如果用户输入了无效数据并提交了没有@valid
注释
ControllerMethod(@modelAttribute("MyEntity") MyEntity MyEntity){
//you have a invalid object of MyEntity.
}
但如果你选择@valid
annotaion
ControllerMethod(@valid @modelAttribute("MyEntity") MyEntity MyEntity,BindingResult result){
//with using @valid annotaion you dont have to check
//if the fields are not null in the myentity object,
//if the myentity object does have errors or incomplete those errors will be stored in
//the result object,so you can simply make a redirect to the form again
if(result.hasErrors()){
//object is invalid return to the form
}else{
//object is valid. you can continue
}
}