普通項目
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>4.1.0.Final</version></dependency><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>2.0.1.Final</version></dependency>
-
編寫校驗工具(使用validator框架校驗工具)
package com.csvn.utils;import com.csvn.blogs.dto.BlogFileDto;
import org.hibernate.validator.HibernateValidator;import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;/*** @author haizhuangbu* @date 2024/5/14 12:56* @mark ValidatorUtils 校驗工具*/
public class ValidatorUtils {private static Validator validator;private static final Object lockObj = new Object();/*** @param o* @return 返回異常信息*/public static String validator(Object o) {Validator validation = getValidation();Set<ConstraintViolation<Object>> validate = validation.validate(o);String errMessage = validate.stream().map(va -> va.getPropertyPath() + " : " + va.getMessage()).collect(Collectors.joining(","));return errMessage;}private static Validator getValidation() {if (validator == null) {synchronized (lockObj) {validator = Validation.byProvider(HibernateValidator.class).configure().buildValidatorFactory().getValidator();}}return validator;}}
BlogFileDto blogFileDto = new BlogFileDto();String validator1 = ValidatorUtils.validator(blogFileDto);System.out.println(validator1);

????????
SpringBoot項目
-
導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
-
接口使用(在接口實體類直接添加@Valid注解)
@PostMapping("/saveContent")public Result<String> saveContentInfo(@Valid @RequestBody ContentInfo contentInfo) {blogsContentInfoService.insertContentInfo(contentInfo);return Result.of("內容插入成功");}
-
通過異常攔截 @ControllerAdvice 獲取校驗異常
package com.csvn.common;import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;import java.util.stream.Collectors;/*** @author haizhuangbu* @date 2024/5/14 17:10* @mark RequestAdivce*/
@RestControllerAdvice
public class RequestAdvice {/*** @param methodArgumentNotValidException 方法參數校驗異常* @return 異常信息*/@ExceptionHandler(value = MethodArgumentNotValidException.class)public Result methodError(MethodArgumentNotValidException methodArgumentNotValidException) {String errorMsg = methodArgumentNotValidException.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));return Result.error(errorMsg);}}
拓展自定義實現參數校驗(字典項校驗)?
-
自定義實現注解
package com.csvn.utils.common;import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Constraint(validatedBy = {NotInMap.NotInMapImp.class}
)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotInMap {String key(); // 字典碼值String message() default "不存在字典項";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};}
-
自定義校驗規則??
class NotInMapImp implements ConstraintValidator<NotInMap, String> {String key;@Overridepublic void initialize(NotInMap annotation) {key = annotation.key();ConstraintValidator.super.initialize(annotation);}@Overridepublic boolean isValid(String value, ConstraintValidatorContext context) {// 查詢數據庫 通過key// select * from s_cde where key = #{key}return false; // obj == null}}
-
最終結果
詳細校驗項(最大值、最小值....注解)https://mp.csdn.net/mp_blog/creation/editor/135977372