Validation


Information resource:

SpringBoot Docs: 2.8.9. @ConfigurationProperties Validation

url: https://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发个请求瞅瞅结果

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

  • 输入非法格式的邮箱

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

Java-Bean Validation后端校验总结的更多相关文章

  1. 深入了解数据校验:Java Bean Validation 2.0(JSR380)

    每篇一句 吾皇一日不退役,尔等都是臣子 相关阅读 [小家Java]深入了解数据校验(Bean Validation):基础类打点(ValidationProvider.ConstraintDescri ...

  2. 1. 不吹不擂,第一篇就能提升你对Bean Validation数据校验的认知

    乔丹是我听过的篮球之神,科比是我亲眼见过的篮球之神.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免 ...

  3. Java bean validation 规范与参考实现

    1.Apache Bval 依赖包:validation-api-1.1.0.Final.jar org.apache.bval.bundle-1.1.1.jar bval-core-1.1.1.ja ...

  4. Java Bean Validation(参数校验) 最佳实践

    转载来自:http://www.cnblogs.com 参数校验是我们程序开发中必不可少的过程.用户在前端页面上填写表单时,前端js程序会校验参数的合法性,当数据到了后端,为了防止恶意操作,保持程序的 ...

  5. Java Bean Validation 最佳实践

    参数校验是我们程序开发中必不可少的过程.用户在前端页面上填写表单时,前端js程序会校验参数的合法性,当数据到了后端,为了防止恶意操作,保持程序的健壮性,后端同样需要对数据进行校验.后端参数校验最简单的 ...

  6. java bean validation 参数验证

    一.前言 二.几种解决方案 三.使用bean validation 自带的注解验证 四.自定义bean validation 注解验证 一.前言 在后台开发过程中,对参数的校验成为开发环境不可缺少的一 ...

  7. Spring validation 后端校验【转】

    本文来自 下一秒升华 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/u013815546/article/details/77248003?utm_source=co ...

  8. SpringBoot - Bean validation 参数校验

    目录 前言 常见注解 参数校验的应用 依赖 简单的参数校验示例 级联校验 @Validated 与 @Valid 自定义校验注解 前言 后台开发中对参数的校验是不可缺少的一个环节,为了解决如何优雅的对 ...

  9. Java Bean validation specification...

    http://www.ibm.com/developerworks/cn/java/j-lo-beanvalid/index.html

随机推荐

  1. Spring WebFlux 基础教程:参数校验

    请求参数校验,在实际的应用中很常见,网上的文章大部分提供的使用注解的方式做参数校验.本文主要介绍 Spring Webflux Function Endpoint 使用 Spring Validati ...

  2. 三年Android开发快手、美团、支付宝连挂,怒刷1549页面试题字节上岸

    刚开始面试的时候我真的是处处碰壁,面一家挂一家,面完之后怀疑自我,是不是自己真的太菜了找不到工作.工作本身就是双向选择,一家不行再换一家,总有合适的,千万不要因为别人的一句话就全盘否定自己,一定要自信 ...

  3. SpringSecurity:简单入门

    SpringSecurity能做什么 SpringSecurity是一个安全框架,使用它可以让我们的系统变得安全一点,它可以对登陆系统的用户进行验证和授权 一个安全的系统需要做的事情很多,比如:防SQ ...

  4. Access Java API in Groovy Script

    $ cat Hello.java package test; public class Hello { public int myadd(int x, int y) { return 10 * x + ...

  5. canvas也能实现事件系统????

    前言 大家好! 我是热爱图形的fly, 之前在群里和粉丝讨论canvas 如何事件系统, 然后呢? 我自己其实也对这个比较感兴趣, 我看过很多canvas 实现的项目, 比如canvas 实现思维导图 ...

  6. weblogicSSRF漏洞复现

    一.关于SSRF 1.1 简介: SSRF(Server-Side Request Forgery)服务端请求伪造,是一种由攻击者构造形成由服务器端发起请求的一个漏洞,一般情况下,SSRF 攻击的目标 ...

  7. STM32—DAC配置

    文章目录 一.DAC介绍 二.主要寄存器说明 三.代码及配置 一.DAC介绍 ADC是模数转换器,可以将模拟电压转换位数字信号:DAC是数模转换器,可以将数字信号转换为模拟电压. STM32F103Z ...

  8. liunx上安装nacos

    下载nacos wget https://github.com/alibaba/nacos/releases/download/1.4.1/nacos-server-1.4.1.tar.gz 启动服务 ...

  9. css内容渐入效果实现

    .fade-in-section { opacity: 0; transform: translateY(20vh); visibility: hidden; transition: opacity ...

  10. C#中的集合类

    集合相当于容器,用于将一系列相似的项组合在一起. 集合可以分为泛型集合类和非泛型集合类. 多数集合类都是派生自ICollection.IComparer.IEnumerable.IList.IDict ...