普通项目
<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