是否可以以与非 MVC 应用程序中的 MVC Controller 中的类似方式验证 POJO 类?
例如:
public class Form {
@NotNull
@Size(min = 4, max = 25)
private String login;
...
}
然后:
Form f = new Form();
f.setLogin("login");
现在我想将它传递给某种 validator ,该 validator 将根据注释测试所有字段,就像 MVC 中的 @Valid 一样。
请注意,我想通过注释验证字段。我不想编写所有验证条件,例如 if (login.lenght() < 4 && ....
这可能吗?
最佳答案
您可以使用 Hibernate Validator,它是 Java Bean Validation 规范的实现 - 在 JDK 环境(无 JEE)中工作,如所述 here
Hibernate Validator 允许您添加注释,然后基于该注释运行验证,如下所示:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<?>> constraintViolations =
validator.validate(objectToValidate);
然后您可以检查constraintViolations集合是否有错误。
关于java - 非 MVC 应用程序中的 Spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32724296/