春天提供了什么额外的好处" @ Valid"与EJB验证相对应的验证注释

时间:2016-08-15 05:03:49

标签: spring ejb

为什么我必须在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额外的注释?

1 个答案:

答案 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
    }
    }
相关问题