首页 > 代码库 > [javax.validation]验证
[javax.validation]验证
package main; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class JavaxValidation { public static void main(String[] args) { Dog d = new Dog(); d.setName("小明"); d.setAge(2); ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); Validator validator = vf.getValidator(); Set<ConstraintViolation<Dog>> set = validator.validate(d); for (ConstraintViolation<Dog> constraintViolation : set) { System.out.println(constraintViolation.getMessage()); } } } class Dog { @NotNull(message = "不能为空") private String name; @Min(value = 1, message = "最少为1") @Max(value = 20, message = "最大为20") private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
用到的jar包为
validation-api-1.0.0.GA.jar
hibernate-validator-4.2.0.Final.jar
slf4j-api-1.6.1.jar
太恶心了,javax.validation不都是官方的东西吗?怎么又要引入了hibernate的。而且用hibernate-validator-4.3.1.Final.jar还存在版本兼容问题,找不到某些类。求科普
[javax.validation]验证
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。