Spring Framework 5.0:组件的验证(Bean验证)、Hibernate Validator入门
来源:互联网 发布:海文工程项目网络计划 编辑:程序博客网 时间:2024/06/15 03:08
组件的验证(Bean验证)
package SpringLean.Users;import org.springframework.beans.factory.annotation.Autowired;// 这是我们的 用户实体类public class UserEntity { private int user_id; private String user_name; private int age; public UserEntity(int user_id, String user_name, int age) { this.user_id = user_id; this.user_name = user_name; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } @Autowired public String toString(){ return "用户信息:" + this.getUser_id() + ":" + this.getUser_name() + ":" + this.getAge(); }}
比如我们有这么一个用户实体类
,其中的属性往往是需要有个验证的:age
不能大于多少,user_name
不能包含非法字符。
当然可以在setter方法里来判断,只不过显得B格有点儿低了。
Spring框架有没有什么高级的处理验证的方式?
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/core.html#validator
package SpringLean.Users;import org.springframework.stereotype.Component;import org.springframework.validation.Errors;import org.springframework.validation.Validator;// 用户验证器@Componentpublic class UserValidator implements Validator { public boolean supports(Class<?> aClass) { // 是 UserEntity类 才验证 return UserEntity.class.equals(aClass); } public void validate(Object o, Errors errors) { // 把o对象强制转化为UserEntity对象 UserEntity userEntity = (UserEntity)o; // 开始验证 if (userEntity.getAge() < 0) { errors.reject("age", "年龄不能小于0"); } else if (userEntity.getAge() > 110) { errors.reject("age", "年龄不能不能大于110"); } }}
写一个验证器类。
如何把这个验证器类和用户实体类相关联?
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/core.html#validation-beanvalidation
还在我们的测试类MyTest
中来演示:
@Component("MyTest")public class MyTest { @Autowired UserValidator userValidator; // 加载UserValidator类 // 写个方法用于检测 public void showUser(UserEntity userEntity){ // 把UserEntity和UserValidator关联后,执行验证 DataBinder dataBinder = new DataBinder(userEntity); dataBinder.setValidator(this.userValidator); dataBinder.validate(); if (dataBinder.getBindingResult().hasErrors()){ // 验证有错误 List<ObjectError> errors = dataBinder.getBindingResult().getAllErrors(); for (ObjectError error : errors){ System.out.println(error.getDefaultMessage()); } }else{ System.out.println("数据验证通过"); } }}
上面代码可以看出:在showUser()
方法接收一个UserEntity
类对象,在该方法中进行了和验证类的关联,并且做了验证的判断处理。
来到入口文件,实例化MyTest类
并调用相关方法测试:
public static void main(String[] args) throws Exception{ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("SpringLean"); context.refresh(); MyTest myTest = context.getBean("MyTest",MyTest.class); UserEntity userEntity = new UserEntity(1,"zhangsan",120); myTest.showUser(userEntity); }
执行程序,控制台输出:
年龄不能不能大于110
思考:
如果我们有很多实体类,是否都需要一个个创建Validator来对期验证?
Hibernate Validator入门
JSR-303 Bean Validation API
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/core.html#validation-beanvalidation-overview
这是一个规范,并不是Spring特有的,Spring框架集成了Bean Validation 1.0 (JSR-303) / 1.1 (JSR-349) / 2.0(JSR-380)
关于Bean Validation
具体可以看:
http://beanvalidation.org/
目前实现该规范的有Hibernate Validator
,文档地址:
http://hibernate.org/validator/
1、使用maven安装。
在pom.xml
文件里:
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.7.Final</version></dependency><dependency> <groupId>org.glassfish</groupId> <artifactId>javax.el</artifactId> <version>3.0.1-b08</version></dependency>
2、改造我们的用户实体类
package SpringLean.Users;import org.springframework.beans.factory.annotation.Autowired;import javax.validation.constraints.Max;import javax.validation.constraints.Min;import javax.validation.constraints.NotNull;// 这是我们的 用户实体类public class UserEntity { private int user_id; @NotNull private String user_name; @NotNull @Min(value = 10, message = "年龄不能小于10") @Max(value = 110, message = "年龄不能大于110") private int age; public UserEntity(int user_id, String user_name, int age) { this.user_id = user_id; this.user_name = user_name; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } @Autowired public String toString(){ return "用户信息:" + this.getUser_id() + ":" + this.getUser_name() + ":" + this.getAge(); }}
注意,我们在几个属性上打上了注解。
3、注册Bean
package SpringLean;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.validation.Validator;import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;@Configuration // 表明这是一个配置类public class MyConfig { @Bean public Validator LocalValidator(){ return new LocalValidatorFactoryBean(); }}
关于注册Bean的方式,这里还是使用的注解的方式,关于这部分知识,可以查看:
http://blog.csdn.net/github_26672553/article/details/78793707
4、然后我们肯定知道在MyTest
类中,就就要验证类换掉了
@AutowiredValidator LocalValidator;
dataBinder.setValidator(this.LocalValidator);
这样就完成了Hibernate Validator的简单使用。
总结:
到这一步,我们可以发现:使用Hibernate Validator的好处就是避免了单独写验证类,通过注解的形式直接在我们的实体类上就可以完成了
- Spring Framework 5.0:组件的验证(Bean验证)、Hibernate Validator入门
- spring MVC中基于hibernate validator的form表单验证
- spring MVC中基于hibernate validator的form表单验证
- Spring MVC基于hibernate validator的数据验证示例
- spring MVC中基于hibernate validator的form表单验证
- spring mvc4 hibernate validator 方法参数验证
- Validator验证框架入门
- springMVC Hibernate Validator验证框架的使用
- 使用Validator做SpringMVC的验证框架 - 自定义验证组件
- spring-mvc的数据验证Validator
- spring mvc 结合Hibernate Validator进行服务器验证
- spring集成JSR-303验证框架--Hibernate-validator实现
- Hibernate Validator验证注解说明
- hibernate验证注解validator用法
- Hibernate Validator验证注解说明
- Hibernate Validator验证注解说明
- Hibernate Validator验证注解说明
- Hibernate Validator验证注解说明
- Spring定时任务,本地正常, Linux服务器跑两次的问题 。。
- AutoCAD 2018 for Mac(CAD三维设计绘图软件) v2018最新破解版
- 前端学习资源分享
- 降序显示前50素数
- js中scroll的简单用法
- Spring Framework 5.0:组件的验证(Bean验证)、Hibernate Validator入门
- POJ3468 A Simple Problem with Integers
- 配置 Ubuntu 环境
- If this view is optional add '@Nullable' (fields) or '@Optional' (methods) ...
- VS2015 + Qt5.7学习心得
- Android studio在打包时候的问题
- unity编辑器拓展九——删除场景中丢失的脚本
- Android 8.0恢复出厂设置
- Redis的RDB(快照)与AOF