Java - custom JSR303 validation

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

Java —— Entity attribute entry parameter non-null verification %252C%2522scm % 2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165078097716782246489271&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog- 2~blog~first_rank_ecpm_v1~rank_v31_ecpm-5-118303844.article_score_rank_blog&utm_term=notnull&spm=1018.2226.3001.4450

        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);
    }

Guess you like

Origin blog.csdn.net/xue_xiaofei/article/details/124381845