SpringMVC: @Valid 表单验证

使用例子

  • Spring Boot 提供了强大的表单验证功能实现

假设我们有一个 Student 实体类

@Entity
@Table(name = "Student")
@Data
public class Student {
    @Id
    @GeneratedValue
    private Integer id;

    @NotEmpty(message = "姓名不能为空!")
    @Column(length = 50)
    private String name;

    @NotNull(message = "年龄不能为空!")
    @Min(value = 18, message = "年龄必须大于18岁!")
    @Column(length = 50)
    private Integer age;
}

Dao 接口

public interface StudentRepository extends JpaRepository<Student,Integer> {}
      ○ Service 接口:
public interface StudentService {
    void add(Student student);
}

Service 接口实现类

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public void add(Student student) {
        studentRepository.save(student);
    }
}

Controller

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @PostMapping(value="/add")
    public String add(@Valid Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return bindingResult.getFieldError().getDefaultMessage();
        }else{
            studentService.add(student);
            return "添加成功!";
        }
    }
}
  • @ValidBindingResult
    • @Valid 注解在参数上,表示让 Spring 验证该参数的属性
    • @Valid 参数后紧跟着一个 BindingResult 参数,用于获取校验结果,否则 Spring 会在校验不通过时抛出异常

校验注解

空检查

  • @Null:限制只能为 null
  • @NotNull:限制不能为 null
  • @NotEmpty:不为 null 且不为空(字符串长度不为0、集合大小不为0)
  • @NotBlank:不为空(不为 null、去除首位空格后的长度为0,与@NotEmpty不同的是字符串比较时会去除字符串的空格)

Boolean检查

  • @AssertFalse:限制必须为false
  • @AssertTrue:限制必须为true

长度检查

  • @Size(max,min):限制长度必须在 min 到 max 之间
  • @Length(min=,max=):长度在 min 到 max 之间

日期检查

  • @Past:验证注解的元素值(日期类型)比当前时间早
  • @Future:限制必须为一个将来的日期
  • @Pattern(value):限制必须符合制定的正则表达式

数值检查

  • @Max(value):限制必须为一个大于指定值的数字
  • @Min(value):限制必须为一个小于指定值的数字
  • @DecimalMax(value):限制必须为一个大于指定值的数字
  • @DecimalMin(value):限制必须为一个小于指定值的数字
  • @Range(min=, max=) :数值在 min 到 max 之间
  • @Digits(integer,fraction):限制必须为一个小数,整数部分位数不能超过integer,小数部分不能超过 fraction

其它检查

  • @Email:验证元素的值时Email
  • @URL(protocol=,host=, port=,regexp=, flags=):请求地址、端口、主机检查
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • 使用ubuntu官方发布的docker镜像进行二次修改 这是一个菜鸟的脚本,执行命令应该是使用 & 连接,一个RU...
    hisenyuan阅读 609评论 0 1
  • 你在天边 眨着一只眼 俏皮 又冷艳 嫦娥 可否还闲 是不是 连玉兔 也孜孜不倦 金星与火星 能不能相见 牛郎和织女...
    骨冰儿阅读 288评论 4 2