springboot 04 jsr303验证

1、介绍

JSR-303是用来校验数据格式的,虽然说前端也可以校验,但是后端校验更安全。

JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation,Hibernate Validator实现 Bean Validation。

JSR是Java Specification Requests的缩写,意思是Java 规范提案。

所以说要使用JSR,需要导入hibernate.validator对应的包

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>7.0.1.Final</version>
</dependency>

但是但是,springboot 集成了它,按照springboot的习惯,我需要一个数据验证的场景,就加入对应的启动器就可以了,所有我们只需要导入下面的启动器到我们的pom.xml文件中就可以了。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

在这里插入图片描述

2、使用

需要在我们的bean上使用@Validated注解,在我们的属性上加验证注解

例如,现在我们有一个学生实体类,我们要求姓名不能为空,长度在2~4个字符,年龄在1 ~ 10岁,就可以这样做。

package cn.butcher.pojo;



import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "student")
@Validated
public class Student {

    @NotNull(message = "姓名不能为空!")
    @Size(min = 2,max = 4,message = "姓名长度在2到4之间!")
    private String name;

    @Max(value = 10,message = "年龄最大为10岁")
    @Min(value = 1,message = "年龄最小为1岁")
    private int age;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

我们在application.yaml文件中对属性进行注入:

# 符合规则的
student:
  name: 谭熙
  age: 3

我们的值正常输出了:
Student{name=‘谭熙’, age=3}

# 不符合规则的
student:
  name:age: 11

我们的值没有正常输出,而是:

Property: student.age
Value: 11
Origin: class path resource [application.yaml] - 3:8
Reason: 年龄最大为10岁
Property: student.name
Value: 谭
Origin: class path resource [application.yaml] - 2:9
Reason: 姓名长度在2到4之间!

3、常见验证

@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;

空检查
@Null       验证对象是否为null
@NotNull    验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank   检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty   检查约束元素是否为NULL或者是EMPTY.
    
Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  
    
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) string is between min and max included.

日期检查
@Past       验证 DateCalendar 对象是否在当前时间之前  
@Future     验证 DateCalendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

(转自狂神)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值