使用javax.validation.constraints包的注解实现校验

一、添加maven依赖包

 <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.1.0.Final</version>
    </dependency>

二、在校验字段上添加校验注解

class Profile{
        @NotNull(message = "字段值不能为空")
        private String name;
        @NotNull
        private String sex;
        @Max(value = 20,message = "最大长度为20")
        private String address;
        @NotNull
        @Size(max=10,min=5,message = "字段长度要在5-10之间")
        private String fileName;
        @Pattern(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$",message = "不满足邮箱正则表达式")
        private String email;
        @AssertTrue(message = "字段为true才能通过")
        private boolean isSave;
        @Future(message = "时间在当前时间之后才可以通过")
        private Date date;

}

三、在Controller层使用@Validated进行验证

@RequestMapping("file/upload")
 public void upload(@RequestPart("files") MultipartFile files, @Validated Profile profile, Errors error) throws IOException {
       if(error.hasErrors()){
           return;
       }
       files.transferTo(new File(files.getOriginalFilename()));保存文件
}

欢迎关注南阁公众号


南阁

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页