利用javax.validation实现对bean属性校验

1.使用场景介绍

controller层对传入的bean的属性进行非空、属性长度等合法性的校验。
传统的方式是我们要自己写if…else…去判断,比较麻烦。

2.实现效果

在这里插入图片描述

3.代码介绍

代码结构:
在这里插入图片描述

pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

3.1 工具类

/**
 * @Description: 校验结果
 * @Author laoxu
 * @Date 2020/5/27 23:30
 **/
@Data
public class ValidationResult {
    // 校验结果是否有错
    private boolean hasErrors;

    // 校验错误信息
    private Map<String, String> errorMsg;
}
public class ValidationUtils {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> ValidationResult validateEntity(T obj) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        // if( CollectionUtils.isNotEmpty(set) ){
        if (set != null && set.size() != 0) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = new HashMap<String, String>();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }

    public static <T> ValidationResult validateProperty(T obj, String propertyName) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
        if (set != null && set.size() != 0) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = new HashMap<String, String>();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(propertyName, cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }

    /**
     * bean整体校验,把所有违规信息,输出String。
     */
    public static String validate(Object o, Class<?>... groups){
        Set<ConstraintViolation<Object>> resultSet=validator.validate(o, groups);
        if(resultSet == null || resultSet.size() ==0){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for(ConstraintViolation<Object> constraintViolation : resultSet) {
            sb.append(constraintViolation.getMessageTemplate()).append(",");
        }
        return sb.substring(0,sb.length()-1);
    }

}

3.2 模型类

@Data
public class Student {
    @Length(max=20,message="姓名长度不能大于20")
    @NotEmpty(message="姓名不能为空")
    private String name;
    @Range(min = 0, max = 1, message = "性别只能输入只能输入0或1")
    private Integer gender;
    private Integer age;
    @Email
    private String email;
    @NotBlank(message = "身份证号不能为空")
    @PhoneNumber
    private String phone;
}

3.3 注解类

/**
 *  自定义验证
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
// 指定真正实现校验规则的类
@Constraint(validatedBy = PhoneValidator.class)
public @interface PhoneNumber {
    String message() default "手机号不合法";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

3.4 实现类

public class PhoneValidator implements ConstraintValidator<PhoneNumber,String> {
    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) 
    {
        return s.length()==11;
    }
}

3.5 控制器

@RestController
@RequestMapping("/api/student")
public class StudentController {
    private static final Logger log = LoggerFactory.getLogger(StudentController.class);

    @PostMapping("add")
    public String add(@RequestBody Student student){
        ValidationResult validationResult = ValidationUtils.validateEntity(student);
        if(validationResult.isHasErrors()){
            return validationResult.getErrorMsg().toString();
        }

        return "添加成功";

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值