SpringBoot2 @validated 自定义效验类型

Posted Archibald Witwicky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot2 @validated 自定义效验类型相关的知识,希望对你有一定的参考价值。

项目参考:详细参见:《Spring Boot 2精髓:从构建小系统到架构分布式大系统》 第三章 3.5.3节 自定义校验

项目结构

 

WorkTime

package com.archibladwitwicke.springboot2.chapter03.validated;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Constraint(validatedBy = { WorkTimeValidated.class })
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD})
public @interface WorkTime {
    String message() default "工作时间不能超过8小时!";

    int max() default 8;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

  

WorkTimeValidated

package com.archibladwitwicke.springboot2.chapter03.validated;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class WorkTimeValidated implements ConstraintValidator<WorkTime, Integer> {

    private int max;

    @Override
    public void initialize(WorkTime work) {
        max = work.max();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        Boolean flag = false;

        if (value == null || value < max) {
            flag = true;
        }

        return flag;
    }
}

  

UserValidated

package com.archibladwitwicke.springboot2.chapter03.pojo;

import com.archibladwitwicke.springboot2.chapter03.validated.WorkTime;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;

public class UserValidated {

    public interface Add {
    }

    public interface Update {
    }

    @NotNull(groups = Update.class)
    @Null(groups = Add.class)
    private Long id;

    @NotNull(message = "名字不能为空!")
    private String name;

    @NotNull(message = "年龄不能为空!")
    @Max(value = 100, message = "年龄不能大于100岁!")
    private String age;

    @NotNull
    @WorkTime(max = 5, message = "工作时间不能超过5小时!")
    private Integer worktime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Integer getWorktime() {
        return worktime;
    }

    public void setWorktime(Integer worktime) {
        this.worktime = worktime;
    }
}

  

ValidateController

package com.archibladwitwicke.springboot2.chapter03.controller;

import com.archibladwitwicke.springboot2.chapter03.pojo.UserValidated;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/validated")
public class ValidatedController {

    @RequestMapping("/validateuser")
    @ResponseBody
    public String validateUser(@Validated UserValidated userValidated, BindingResult bindingResult) {
        String result = null;

        if (bindingResult.getErrorCount() == 0) {
            result = "通过验证!";
        }

        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError error : allErrors) {
            String defaultMessage = error.getDefaultMessage();
            System.out.println(defaultMessage);
        }

        return result;
    }


    @RequestMapping("/validateusergroup")
    @ResponseBody
    public String validateUserByGroup(@Validated UserValidated userValidated, BindingResult bindingResult) {
        String result = null;

        if (bindingResult.getErrorCount() == 0) {
            result = "通过验证!";
        }

        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError error : allErrors) {
            String defaultMessage = error.getDefaultMessage();
            System.out.println(defaultMessage);
        }

        return result;
    }
}

  

 

以上是关于SpringBoot2 @validated 自定义效验类型的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot2 hikari关于 Failed to validate connection com.mysql.cj.jdbc.ConnectionImpl处理

Springboot 2.0.x Redis缓存Key生成器,自定义生成器

SpringBoot2.3.x-JSR303效验不显示

SpringBoot2.3.x-JSR303效验不显示

Spring Boot 2.2.2 和“hibernate.hbm2ddl.auto=(create|create-drop|update|validate)”不起作用

MethodValidationInterceptor 和 @Validated @ModelAttribute