Java-Bean Validation后端校验总结

Validation


Information resource:

SpringBoot Docs: 2.8.9. @ConfigurationProperties Validation

url: //docs.spring.io/spring-boot/docs/2.3.12.RELEASE/reference/html/spring-boot-features.html#boot-features

Spring Boot attempts to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation. You can use JSR-303 javax.validation constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example:

每当使用 Spring 的 @Validated 注释时,Spring Boot 都会尝试验证 @ConfigurationProperties 类。 可以直接在配置类上使用 JSR-303 javax.validation 约束注释。 为此,请确保类路径上有一个兼容的 JSR-303 实现,然后向字段添加约束注释,如以下示例所示:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

You can also trigger validation by annotating the @Bean method that creates the configuration properties with @Validated.

还可以通过注释使用@Validated 创建配置属性的@Bean 方法来触发验证。

To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with @Valid. The following example builds on the preceding AcmeProperties example:

为确保始终为嵌套属性触发验证,即使未找到任何属性,也必须使用 @Valid 注释关联字段。 以下示例建立在前面的 AcmeProperties 示例之上:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

    @NotNull
    private InetAddress remoteAddress;

    @Valid
    private final Security security = new Security();

    // ... getters and setters

    public static class Security {

        @NotEmpty
        public String username;

        // ... getters and setters
    }
}

JSR-303 Validation


JSR-303 是Java EE的一个子规范,官方参考实现Hibernate Validator

JSR-303 是一个数据验证的规范,而Hibernate Validator则是实现了这一规范,可以使用注解的方式对Bean进行验证,它的内部已经定义好了一系列的限制注解,只需将需要的注解标注在需要验证的实体类的属性上或者是对应的get方法上即可

JSR-303常用校验规则

布尔检查

注解 描述
@AssertFalse 被标注的对象是否为False
@AssertTrue 被标注的对象是否为True

空值检查

注解 描述
@Null 验证被标注的对象是否为NULL
@NotNull 验证被标注的对象是否不为NULL
@NotBlank 验证字符串是否非空,trim()后不为””,长度大于0
@NotEmpty 验证被标注对象是否为非空

长度检查

注解 描述
@Length(min,max) 验证字符串长度是否在min,max范围内
@Size(min,max) 验证对象(Collection,String,Map,Array)是否在规定范围内

日期检查

注解 描述
@Past 验证时间对象的值是否在当前时间之前
@Future 验证时间对象的值是否在当前时间之后
@Pattern(regexp) 验证字符串是否符合指定的正则表达式

数值检查

注解 描述
@Email 验证被标注对象是否为邮箱格式,NULL值不验证
@Valid 关联对象是数组或集合时,对其元素进行校验
@Digits(integer,fraction) 验证字符串是否是符合指定格式的数字,integer整数精度,fraction小数精度
@Min 验证字符串是否是大于Min指定的最小值的数字
@Max 验证字符串是否是小于Max指定的最大值的数字
@Range(min,max) 验证元素是否在min,max范围内

使用Hibernate Validator的Demo

Demo的项目结构:

pom.xml

<!-- 使用的是hibernate validator -->
<dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>${hibernate-validator.version}</version>
</dependency>

User(Bean)

/**
 * @Email 约束输入邮件的格式
 * @NotBlank 指字符串使用trim()去掉前后空格后,不能够为空
 */
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User implements Serializable {

    @NotBlank(message = "邮箱不能为空")
    @Email(message = "邮箱非法")
    private String userEmail;

    @NotBlank(message = "电话不能为空")
    @Pattern(regexp = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$",message = "手机号非法")
    private String userPhone;
}

UserController

/**
 * 以POST请求为例
 * @Validated 注释类
 * @RequestBody 可传Javabean类型
 * @RequestParam 传单个参数
 * @Valid 修饰在Javabean类型前
 */
@RestController
@Validated
public class UserController {

    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public boolean test(@RequestBody @Valid User user){
        return true;
    }

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(){
        return "hello,world";
    }
}

Rusult:Postman发个请求瞅瞅结果

  • 输入正确格式的邮箱和手机

  • 输入非法格式的邮箱

  • 输入非法格式的手机号码