在真實的開發中,我們經常會遇到需要對數據進行校驗的業務,那么本篇文章對此進行總結。暫時總結三種方法,大家可以根據需要選擇使用。
一、Java Bean Validation 驗證 【校驗處理】一、Java Bean Validation驗證
二、SpringBoot Validate 統一處理 【校驗處理】二、SpringBoot Validate 統一處理
三、Spring Validation 校驗處理 【校驗處理】三、Spring Validation 校驗處理
本篇文章采用第一種Java Bean Validation的驗證方式。話不多說,直接上代碼。
1. 引入依賴
注意:java bean validation參數驗證,在使用的時候,有時候會報錯,原因是跟spring版本不兼容,這里演示的版本如下:
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.1.Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.1.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency>
2. 測試實體類
注意:將需要的校驗規則直接通過注解寫在實體類對應字段上即可
@Data @AllArgsConstructor public class Test { @Length(min = 1,max = 5,message = "姓名長度應該在1-5之間") private String name; @Range(min = 1,max = 100,message = "年齡應該在1-100之間") private Integer age; @DecimalMax(value = "100.00",message = "體重有些超標哦") @DecimalMin(value = "60.00",message = "多吃點飯吧") private BigDecimal weight; @Future(message = "元素必須是一個將來的日期") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date date; @AssertTrue(message = "此值只能為true") private Boolean isuser; @Email(message = "郵箱地址無效") private String email; }
3. 校驗工具類
注意:
(1)如果想要使用,直接調用ValidationUtils.validate參數直接傳實體對象即可。
(2)validate方法可以優化,常見的是新建一個set集合,將所有的提示消息放到set中之后返回即可。
public class ValidationUtils implements Serializable { public static void main(String[] args) { Test test = new Test("張三張三張三",0,new BigDecimal(110.00),new Date(),false,"12345"); validate(test); } private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); public static <T> String validate(T t) { try { Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); for (ConstraintViolation<T> constraintViolation : constraintViolations) { System.out.println("invalidvalue: "+constraintViolation.getInvalidValue() == null?"":constraintViolation.getInvalidValue().toString()+" propertypath: "+constraintViolation.getPropertyPath()+" message: "+constraintViolation.getMessage()); } } catch (Exception e) { e.printStackTrace(); } return ""; } }
4. 總結一波實體類上支持的注解

參考:
1. https://www.cnblogs.com/xiaogangfan/p/5987659.html
2. https://cloud.tencent.com/developer/ask/126580
持續更新!!!
