当前端传参数都后端的时候,对参数进行格式验证,邮箱、非空等验证。
一般是在前端js中进行校验,在后端也可以通过JSR303校验。
1.实体类校验
在实体类上添加 @Validated注解。
然后在类变量上添加相关校验
添加引用
import org.springframework.validation.annotation.Validated;
@Data
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class User{
@Email(message = "邮箱格式错误")
private String eamil;
private String name;
private Integer age;
}
2.参数校验
@Controller
@PostMapping("/hello")
public class Hellocontroller {
@GetMapping("/hello")
@ResponseBody
public Person hello(@Validated Person person){
return person;
}
}
3.注意事项
在使用 @Email注解是报错
Cannot resolve symbol ‘Email’
我是用的是sprignboot2.5.6版本,该依赖被移除,需要添加相应以来,早期版本是不用添加的,可以根据使用版本判断
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
4.常用注解
注解 功能
@Null 对象必须为null
@NotNull 对象必须不为null,无法检查长度为0的字符串
@NotBlank 字符串必须不为Null,且去掉前后空格长度必须大于0
@NotEmpty 字符串必须非空
@Length(min = 1,max = 50) 字符串必须在指定长度内
@Range(min = 0,max = 100) 必须在指定范围内
@AssertTrue 对象必须为true
@AssertFalse 对象必须为false
@Max(Value) 必须为数字,且小于或等于Value
@Min(Value) 必须为数字,且大于或等于Value
@DecimalMax(Value) 必须为数字( BigDecimal ),且小于或等于Value。小数存在精度
@DecimalMin(Value) 必须为数字( BigDecimal ),且大于或等于Value。小数存在精度
@Digits(integer,fraction) 必须为数字( BigDecimal ),integer整数精度,fraction小数精度
@Size(min,max) 对象(Array、Collection、Map、String)长度必须在给定范围
@Email 字符串必须是合法邮件地址
@Past Date和Calendar对象必须在当前时间之前
@Future Date和Calendar对象必须在当前时间之后
@Pattern(regexp=“正则”) 字符串满足正则表达式的值