Spring MVC中的验证器

Amo*_*ogh 1 spring-mvc bean-validation

我们在Spring MVC中使用@ Min,@ Max,@ NotNull等注释进行服务器端验证.这些注释应该放在Model Class中.我希望在需要时应用这样的注释,我不想在Model类中应用这样的注释.

例如.

我有一个具有属性名称,性别,电子邮件的人员.如果我将@NotNull注释放在电子邮件属性上,那么它将获得全局应用,如果我的要求发生变化,就好像在我的系统中有两个人学生和教师和教师注册电子邮件是可选的但是对于学生它不是null那么我怎么能得到这个.

在上述例子的情况下,我可以动态地应用验证注释 -

如果UserRegistration是For Teacher,那么Email是可选的.

如果UserRegistration是For Student,则电子邮件是强制性的.

Sla*_*hin 5

为了实现这种行为,我建议使用动态激活的组.看看我的例子.

Person.java:

class Person {

    @NotNull(groups = StudentChecks.class)
    @Email
    private email;

    // other members with getters/setters

    public interface StudentChecks {
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,@NotNull只有在StudentChecks激活组时才会执行约束.要按条件激活验证组,Spring提供了特殊注释@Validated.

StudentController.java:

@Controller
public class StudentController {

    @RequestMapping(value = "/students", method = RequestMethod.POST)
    public String createStudent(@Validated({Person.StudentChecks.class}) Person student, BindingResult result) {
        // your code
    }

}
Run Code Online (Sandbox Code Playgroud)

您可以在那里找到更多细节: