SpringBoot+JSR303
依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
-
框架自带校验
-
entity设置
-
@Data @Builder public class Employee implements Serializable { public interface Operation {} public interface Query extends Operation{} public interface Update extends Operation{} public interface Save extends Operation{} public interface Delete extends Operation{} //激活子父也会激活,激活父不会激活子 @Range(min = 0L,max = 1000L,groups = {Operation.class}) @NotNull(groups = {Query.class}) private Integer id; }
-
-
controller设置
-
@PostMapping("/employee") public String getEmployee(@RequestBody @Validated(Employee.Operation.class) Employee employee, BindingResult bindingResult) { if (bindingResult.hasErrors()){ List<FieldError> allErrors = bindingResult.getFieldErrors(); String error = ""; for (FieldError fieldError : allErrors) { error += fieldError.getObjectName()+fieldError.getField()+fieldError.getDefaultMessage(); } return error; } List<Employee> employees = employeeService.selectByExample(employee); return employees.toString(); }
-
-
通用校验异常
-
class A {}
-
-
-
自定义校验类
-
@Documented //注解使用的校验器 @Constraint( validatedBy = {AgeValidator.class} ) @SupportedValidationTarget({ValidationTarget.ANNOTATED_ELEMENT}) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @ReportAsSingleViolation public @interface Age { int min() default 0; int max() default 125; //{max}用来获取参数值 String message() default "年龄是非法的,最大不能超过{max}岁,最小不能小于{min}岁"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
-
public class AgeValidator implements ConstraintValidator<Age,Integer> { private Integer max; private Integer min; @Override public void initialize(Age constraintAnnotation) { this.max = constraintAnnotation.max(); this.min = constraintAnnotation.min(); } @Override public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) { return integer != null && integer < max && min < integer; } }
-
-
配置全局异常捕获参数校验错误
-
配置全局异常类
-
/** * @author QianShuang */ //包路径不能写表达式 *.**.controller @RestControllerAdvice(basePackages = "com.miracle.springdemo.controller") public class ValidatorErrorControllerAdvice { @ExceptionHandler(value = {MethodArgumentNotValidException.class,BindException.class}) //入参可以是request对象 public Map<String,String> defaultValidatorErrorHandle(Exception exception) { BindingResult bindingResult; if (exception instanceof MethodArgumentNotValidException) { bindingResult = ((MethodArgumentNotValidException)exception).getBindingResult(); }else { bindingResult = ((BindException)exception).getBindingResult(); } Map<String,String> result = new HashMap<>(16); result.put("对象名称", bindingResult.getObjectName()); bindingResult.getFieldErrors().forEach(fieldError -> { result.put(fieldError.getField(),fieldError.getDefaultMessage()); }); result.put("status","400"); return result; } }
-
-
校验类编写
-
//BindingResult bindingResult对象不用添加在参数列表会直接抛出异常,通过全局异常捕获即可 @PostMapping("/employee") public String getEmployee(@RequestBody @Validated(Employee.Query.class) Employee employee) { List<Employee> employees = employeeService.selectByExample(employee); return employees.toString(); }
-
-