JSR303
JSR303 technology, JSR-303 is a sub-standard in JAVA EE 6, which is often used to verify the validity of interface input parameters. How to use can refer to
But we noticed that the verification method provided by valid is limited. What should we do if we want to customize the verification method? Next, the verification of cron validity will be taken as an example to describe in detail.
add dependencies
It is recommended to use the dependencies under spring instead of javax, and the version can use the current spring version.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>${spring-boot.version}</version>
</dependency>
Customize Validator for cron validity verification
Core validation logic.
public class CronValueConstraintValidator implements ConstraintValidator<CronValue,String> {
@Override
public void initialize(CronValue constraintAnnotation) {
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (!StringUtils.isEmpty(s)) {
return CronExpression.isValidExpression(s);
}
return true;
}
}
Custom cron verification annotation
Custom annotations.
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {CronValueConstraintValidator.class})
public @interface CronValue {
String message() default "cron表达式不合法";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int [] vals() default {};
}
global exception catch
@ExceptionHandler(MethodArgumentNotValidException.class)
public void handlerMethodArgument(HttpServletRequest request, HttpServletResponse response, MethodArgumentNotValidException e) {
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
String msg = fieldErrors.get(0).getDefaultMessage();
log.error("校验失败,信息为{}", msg);
}