欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java接口数据校验

程序员文章站 2024-03-25 10:58:22
...

validation 实现java接口校验

-1.所需依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
  <version>2.2.2.RELEASE</version>
  <scope>compile</scope>
  <exclusions>
    <exclusion>
      <artifactId>tomcat-embed-el</artifactId>
      <groupId>org.apache.tomcat.embed</groupId>
    </exclusion>
  </exclusions>
</dependency>
  • 2.controller测试代码
@RequestMapping("/test3")
    public String addBatch(@RequestBody @Valid CtResultDto data, BindingResult result) {
        if (result.hasErrors()) {
            StringBuffer errorStr = new StringBuffer();
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(error -> {
                errorStr.append(error.getField()).append("->").append(error.getDefaultMessage()).append(";");
            return errorStr.toString();
        }
        return "success";
    }
  • 实体类测试代码
//实体1
@Data
public class CtResultDto extends HosCtResultVo {
    @Valid
    public List<HosCtTubercleInfoPO> ctTubercleInfoPOList;
    @Valid
    public HosPersonInfoPO hosPersonInfoPO;
    @NotNull(message = "CT业务表id不能为空")
    private Integer ctRecordStatusId;   //CT业务表id
    @NotNull
    @Min(value = 1,message = "录入状态必须大于1")
    @Max(value = 2,message = "录入状态必须小于2")
    private Integer inputStatus;   //录入状态 1 提交 3保存草稿
    private Integer checkInfoId;
}
//实体2
@Data
public class HosCtResultVo implements Serializable {
    @NotNull(message="机构id不能为空")
    @Min(0)
    @Max(Integer.MAX_VALUE)
    private Integer deptId;
    @NotNull(message="检查日期不能为空")
    private Date examinationDate;
    @Pattern(regexp = "^1[3|4|5|7|8][0-9]{9}$", message = "用户手机号不合法")
    private String phone;
}
//实体3
@Data
public class HosPersonInfoPO implements Serializable {
    @NotNull(message = "HosPersonInfoPO.id不能为null")
    @Min(value = 10,message = "HosPersonInfoPO.id最小值为10")
    private Integer id;
}
//实体4
@Data
public class HosCtTubercleInfoPO implements Serializable {
    @NotNull(message = "HosCtTubercleInfoPO.id 不能为null")
    private Integer id;
}
  • 入参
{"type":1,"hosPersonInfoPO":{"id":1},"ctTubercleInfoPOList":[{}]}
  • 校验结果
examinationDate->检查日期不能为空;deptId->机构id不能为空;hosPersonInfoPO.id->HosPersonInfoPO.id最小值为10;ctRecordStatusId->CT业务表id不能为空;inputStatus->不能为null;ctTubercleInfoPOList[0].id->HosCtTubercleInfoPO.id 不能为null;

注意:@NotEmpty只能用作String类型的校验;@Size用作校验List类型的size