自定义校验注解

自定义校验注解

自定义校验注解说明引入依赖自定义注解实现ConstraintValidator接口编写自己的校验逻辑编写需要校验实体类测试结果

说明

本文主要是自己实现一个字符串中包含空格的校验,如果包含空格就报错提醒

引入依赖

 
            org.springframework.boot
            spring-boot-starter-validation
 

自定义注解

package com.kang.poi.annotation;
​
import com.kang.poi.validator.NotContainSpacesValidator;
​
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
​
@Documented
@Constraint(
    validatedBy = {NotContainSpacesValidator.class}
)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(NotContainSpaces.List.class)
public @interface NotContainSpaces {
    String message() default "{com.kang.poi.annotation.NotContainSpaces.message}";
​
    Class[] groups() default {};
​
    Class[] payload() default {};
​
    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface List {
        NotContainSpaces[] value();
    }
}

实现ConstraintValidator接口编写自己的校验逻辑

package com.kang.poi.validator;
​
import com.kang.poi.annotation.NotContainSpaces;
import org.apache.commons.lang3.StringUtils;
​
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
​
/**
 * @Author Emperor Kang
 * @ClassName RemoveAllSpacesValidator
 * @Description 去除所有的空格校验器
 * @Date 2023/5/23 18:10
 * @Version 1.0
 * @Motto 让营地比你来时更干净
 */
public class NotContainSpacesValidator implements ConstraintValidator {
    @Override
    public void initialize(NotContainSpaces constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }
​
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if(StringUtils.isBlank(value)){
            return true;
        }
        return !value.contains("") || !value.contains(" ");
    }
}

编写需要校验实体类

package com.kang.poi.pojo;
​
import cn.afterturn.easypoi.excel.annotation.Excel;
import com.kang.poi.annotation.NotContainSpaces;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
​
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
​
/**
 * @Author Emperor Kang
 * @ClassName ExcelUser
 * @Description TODO
 * @Date 2023/5/23 11:06
 * @Version 1.0
 * @Motto 让营地比你来时更干净
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ExcelUser extends ExcelVerifyInfo implements Serializable {
    private static final long serialVersionUID = 3329546401810928144L;
​
    @Excel(name = "用户名",orderNum = "0",isImportField = "true",width = 15)
    @NotBlank(message = "用户名:name不允许为空")
    @NotContainSpaces(message = "不能含有空格")
    private String name;
​
    @Excel(name = "年龄",orderNum = "1",isImportField = "true",width = 15)
    @NotNull(message = "年龄不允许为空")
    private Integer age;
​
    @Excel(name = "地址",orderNum = "2",isImportField = "true",width = 20)
    @NotBlank(message = "地址:address不允许为空")
    @NotContainSpaces(message = "不能含有空格")
    private String address;
​
    @Excel(name = "学校",orderNum = "3",isImportField = "true",width = 15)
    @NotBlank(message = "学校:school不允许为空")
    @NotContainSpaces(message = "不能含有空格")
    private String school;
}
package com.kang.poi.pojo;
​
import cn.afterturn.easypoi.handler.inter.IExcelDataModel;
import cn.afterturn.easypoi.handler.inter.IExcelModel;
​
/**
 * @Author Emperor Kang
 * @ClassName ExcelVerifyInfo
 * @Description TODO
 * @Date 2023/5/23 15:12
 * @Version 1.0
 * @Motto 让营地比你来时更干净
 */
public class ExcelVerifyInfo implements IExcelModel, IExcelDataModel {
    /**
     * 报错信息
     */
    private String errorMsg;
​
    /**
     * 报错的行数
     */
    private int rowNum;
​
​
    @Override
    public Integer getRowNum() {
        return rowNum;
    }
​
    @Override
    public void setRowNum(Integer rowNum) {
        this.rowNum = rowNum + 1;
    }
​
    @Override
    public String getErrorMsg() {
        return errorMsg;
    }
​
    @Override
    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}

测试

  @PostMapping("/import3")
    public Object batchImport3(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setNeedVerify(true);
        ExcelImportResult excelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), ExcelUser.class, importParams);
        List failList = excelImportResult.getFailList();
        Workbook failWorkbook = excelImportResult.getFailWorkbook();
        List list = excelImportResult.getList();
        Map map = excelImportResult.getMap();
        Workbook workbook = excelImportResult.getWorkbook();
        log.info("failList:{}",JSON.toJSONString(failList));
        log.info("list:{}",JSON.toJSONString(list));
        log.info("map:{}",JSON.toJSONString(map));
        List errList = new ArrayList<>();
        if(excelImportResult.isVerifyFail() && !CollectionUtils.isEmpty(failList)){
            failList.stream().forEach(item -> {
                log.info("第{}行,校验不通过, 校验信息为:{}",item.getRowNum(),item.getErrorMsg());
                StringBuilder stringBuilder = new StringBuilder().append("第")
                        .append(item.getRowNum())
                        .append("行")
                        .append("校验不通过,校验错误信息为:")
                        .append(item.getErrorMsg())
                        .append(";");
                errList.add(stringBuilder.toString());
            });
        }
        return errList;
    }

结果

2023-05-23 18:58:27.214  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : failList:[{"age":6,"errorMsg":"地址地址:address不允许为空","name":"name_01","rowNum":2,"school":"牛逼小学_01"},{"address":"上海市浦东新区_2","age":7,"errorMsg":"用户名用户名:name不允许为空","rowNum":3,"school":"牛逼小学_02"},{"address":"上海市浦  东新区_3","age":8,"errorMsg":"地址不能含有空格","name":"name_03","rowNum":4,"school":"牛逼小学_03"},{"address":"上海市浦  东新区_4","age":9,"errorMsg":"地址不能含有空格,用户名不能含有空格","name":"nam e_04","rowNum":5,"school":"牛逼小学_04"},{"address":"上海市浦 东新区_6","age":11,"errorMsg":"地址不能含有空格,用户名不能含有空格","name":"nam e_06","rowNum":7,"school":"牛逼小学_06"},{"age":13,"errorMsg":"地址地址:address不允许为空","name":"name_08","rowNum":9,"school":"牛逼小学_08"}]
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : list:[{"address":"上海市浦东新区_5","age":10,"name":"name_05","rowNum":6,"school":"牛逼小学_05"},{"address":"上海市浦东新区_7","age":12,"name":"name_07","rowNum":8,"school":"牛逼小学_07"},{"address":"上海市浦东新区_9","age":14,"name":"name_09","rowNum":10,"school":"牛逼小学_09"},{"address":"上海市浦东新区_10","age":15,"name":"name_10","rowNum":11,"school":"牛逼小学_10"},{"address":"上海市浦东新区_11","age":16,"name":"name_11","rowNum":12,"school":"牛逼小学_11"},{"address":"上海市浦东新区_12","age":17,"name":"name_12","rowNum":13,"school":"牛逼小学_12"},{"address":"上海市浦东新区_13","age":18,"name":"name_13","rowNum":14,"school":"牛逼小学_13"}]
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : map:null
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : 第2行,校验不通过, 校验信息为:地址地址:address不允许为空
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : 第3行,校验不通过, 校验信息为:用户名用户名:name不允许为空
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : 第4行,校验不通过, 校验信息为:地址不能含有空格
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : 第5行,校验不通过, 校验信息为:地址不能含有空格,用户名不能含有空格
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : 第7行,校验不通过, 校验信息为:地址不能含有空格,用户名不能含有空格
2023-05-23 18:58:27.215  INFO 22328 --- [io-10077-exec-1] com.kang.poi.controller.ExcelController  : 第9行,校验不通过, 校验信息为:地址地址:address不允许为空

你可能感兴趣的:(spring,mybatis,java)