1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、JSR-303 注解介绍
这里只列举了 javax.validation 包下的注解,同理在 spring-boot-starter-web 包中也存在 hibernate-validator 验证包,里面包含了一些 javax.validation 没有的注解,有兴趣的可以看看
| 注解 | 说明 |
|---|---|
@NotNull |
限制必须不为null |
@NotEmpty |
验证注解的元素值不为 null 且不为空(字符串长度不为0、集合大小不为0) |
@NotBlank |
验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格 |
@Pattern(value) |
限制必须符合指定的正则表达式 |
@Size(max,min) |
限制字符长度必须在 min 到 max 之间(也可以用在集合上) |
@Email |
验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式 |
@Max(value) |
限制必须为一个不大于指定值的数字 |
@Min(value) |
限制必须为一个不小于指定值的数字 |
@DecimalMax(value) |
限制必须为一个不大于指定值的数字 |
@DecimalMin(value) |
限制必须为一个不小于指定值的数字 |
@Null |
限制只能为null(很少用) |
@AssertFalse |
限制必须为false (很少用) |
@AssertTrue |
限制必须为true (很少用) |
@Past |
限制必须是一个过去的日期 |
@Future |
限制必须是一个将来的日期 |
@Digits(integer,fraction) |
限制必须为一个小数,且整数部分的位数不能超过 integer,小数部分的位数不能超过 fraction (很少用) |
3、添加验证
由于方法入参可以是基本数据类型,也可以是对象,因此验证可以加在对象的属性上,也可以直接在Controller入参上添加
(1)在对象属性上添加验证
package com.example.demo.entity; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.Email; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import java.util.Date; @Data public class UserValidated { @NotBlank(message = "username不允许为空") @Length(min = 4,max = 8,message = "username长度要在4-8之间") private String username; @Email(message = "邮箱格式不正确") private String email; @Max(value = 200,message = "年龄最大不能超过200") @Min(value = 10,message = "年龄最小不能小于10岁") private int age; private Date date; }
(2)Controller入参添加验证
@Validated
@Controller
@RequestMapping("/test")
@Api(value = "SpringBoot测试接口2")
public class UserTestController2 {
@ResponseBody @PostMapping(value ="/validated") @ApiOperation(value="validated表单验证测试") @ApiImplicitParams( {@ApiImplicitParam(paramType="query", name = "email", value = "邮箱", dataType = "String"), @ApiImplicitParam(paramType="query", name = "username", value = "用户名", dataType = "String"), @ApiImplicitParam(paramType="query", name = "age", value = "年龄", dataType = "String")}) public String validated(@NotBlank(message = "username不允许为空") @Length(min = 4,max = 8,message = "username长度要在4-8之间") String username, @Email(message = "邮箱格式不正确")String email, @Max(value = 200,message = "年龄最大不能超过200") @Min(value = 10,message = "年龄最小不能小于10岁")int age){ return "OK"; }
}
说明:无论是哪一种方式的验证,Controller类上必须添加@Validated注解以打开验证。
4、验证

原文:https://www.cnblogs.com/liconglong/p/11720580.html