SpringBoot 通用Validator
第一步,pom.xml引入hibernate-validator
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
第二步,编写验证结果Bean,存放“验证是否有错误和错误信息”
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
public class ValidationResult {
// 校验结果是否有错
private boolean hasErrors = false;
// 存放错误信息的Map
private Map<String, String> errorMsgMap = new HashMap<>();
public boolean isHasErrors() {
return hasErrors;
}
public void setHasErrors(boolean hasErrors) {
this.hasErrors = hasErrors;
}
public Map<String, String> getErrorMsgMap() {
return errorMsgMap;
}
public void setErrorMsgMap(Map<String, String> errorMsgMap) {
this.errorMsgMap = errorMsgMap;
}
// 将所有的错误信息拼接成一个字符串
public String getErrorMsg(){
return StringUtils.join(errorMsgMap.values().toArray(), ",");
}
}
第三步,
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
/**
* InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。
* Spring初始化完成后,会回调ValidatorImpl的afterPropertiesSet()方法
*/
@Component
public class ValidatorImpl implements InitializingBean {
// 注意需要引用: javax.validation.Validator
private Validator validator;
// 实现校验方法并返回校验结果
public ValidationResult validate(Object bean){
ValidationResult validationResult = new ValidationResult();
Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
if(constraintViolationSet.size() > 0){
// 大于0 表示有错误
validationResult.setHasErrors(true);
for (ConstraintViolation<Object> constraintViolation : constraintViolationSet) {
String errorMsg = constraintViolation.getMessage();
String propertyName = constraintViolation.getPropertyPath().toString();
validationResult.getErrorMsgMap().put(propertyName, errorMsg);
}
}
return validationResult;
}
@Override
public void afterPropertiesSet() throws Exception {
// 将hibernate validator通过工厂的初始化方式使其实例化
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
}
第四步,在Model中定义限制条件,并在业务逻辑中使用验证
public class UserModel {
private Integer id;
@NotBlank(message = "name不能为空")
private String name;
@NotNull(message = "性别不能为空")
private Byte gender;
@NotNull(message = "年龄不能为空")
@Min(value = 0, message = "年龄必须小于0")
@Max(value = 150, message = "年龄不能大于150")
private Integer age;
@NotNull(message = "手机号码不能为空")
@Size(min = 11, max = 11, message = "手机号码必须为11位")
private String telphone;
@NotNull(message = "注册方式不能为空")
private String registerMode;
private String thirdPartyId;
@NotNull(message = "密码不能为空")
private String encrptPassword;
}
======================================================
ValidationResult validationResult = validator.validate(userModel);
if(validationResult.isHasErrors()){
throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR, validationResult.getErrorMsg());
}
SpringBoot 通用Validator的更多相关文章
- SpringBoot使用validator校验
在前台表单验证的时候,通常会校验一些数据的可行性,比如是否为空,长度,身份证,邮箱等等,那么这样是否是安全的呢,答案是否定的.因为也可以通过模拟前台请求等工具来直接提交到后台,比如postman这样的 ...
- SpringBoot 通用返回类设计
在项目中通常需要为前端设计通过的返回类,返回的格式为: { "status": "success", "data": {...} } 定义通 ...
- SpringBoot 通用Error设计
在项目中需要设计统一的错误消息,通常使用枚举类定义"错误码"与"错误消息": 并且也可以做错误消息自定义. 定义通过错误接口类:CommonError publ ...
- springboot 通用Mapper使用
https://blog.csdn.net/dwf_android/article/details/79359360 https://www.cnblogs.com/larryzeal/p/58741 ...
- 【springboot】validator枚举值校验
转自: https://blog.csdn.net/aiyaya_/article/details/78588200 一.前言 在spring项目中,校验参数功能使用hibernate validat ...
- SpringBoot学习历程
新年新气象,更新了一下本人所有写的关于SpringBoot的文章目录,感谢大家长期以来的支持,在接下来的日子还会不定期的进行更新. 入门 使用IntelliJ Idea新建SpringBoot项目 S ...
- 【springboot】知识点总结
[springboot 基础编] 01.SpringBoot>01 - 第一个应用–HelloWorld 02.SpringBoot>02 - 整合 MyBatis 03.SpringBo ...
- 通用mapper版+SpringBoot+MyBatis框架+mysql数据库的整合
转:https://blog.csdn.net/qq_35153200/article/details/79538440 开发环境: 开发工具:Intellij IDEA 2017.2.3 JDK : ...
- 在Spring-Boot中实现通用Auth认证的几种方式
code[class*="language-"], pre[class*="language-"] { background-color: #fdfdfd; - ...
随机推荐
- Android 最新L版本,都更新什么东西了
Android L版本重大修改 一:New Android Runtime (ART) 新的运行环境,4.4一下的版本ART是可选的运行环境,默认还是Dalvik.但是在Android L版本之后默认 ...
- < 转载 > 说说JSON和JSONP
推荐博文---说说JSON和JSONP,也许你会豁然开朗,含jQuery用例 里头说的很详细!
- MySQL索引使用:字段为varchar类型时,条件要使用''包起来
结论: 当MySQL中字段为int类型时,搜索条件where num='111' 与where num=111都可以使用该字段的索引.当MySQL中字段为varchar类型时,搜索条件where nu ...
- 深入理解line
什么是行间距? 古时候我们使用印刷机来出来文字.印刷出来的每个字,都位于独立的一个块中. 行间距,即传说中控制两行文字垂直距离的东东.在CSS中,line-height被用来控制行与行之间垂直距离. ...
- Android UI开发第二十八篇——Fragment中使用左右滑动菜单
Fragment实现了Android UI的分片管理,尤其在平板开发中,好处多多.这一篇将借助Android UI开发第二十六篇——Fragment间的通信. Android UI开发第二十七篇——实 ...
- 邱老师玩游戏(树形DP) UESTC - 1136
邱老师最近在玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中邱老师允许攻克M个城堡并获得里面的宝物. 但由于地理位置原因,有些城堡不能直接攻克,要攻克这些城堡必须先攻克其 ...
- 巨蟒django之CRM3 添加和编辑客户&&公户和私户的展示和转换
昨日内容回顾: day66 1. 内容回顾 1. 数据的展示 数据通过ORM查询出来 对象列表 QuerySet 1. 普通的字段 对象.字段名 ——> 数据库中的值 2. choices (( ...
- 巨蟒python全栈开发django9:一些知识点的汇总
回顾上周内容: 题目: 1.人民出版社出版过的所有书籍的名字以及作者的姓名(三种写法,笔记中有两种写法) 2.手机以2开头的作者出版过的所有书籍名称以及出版社名称(三种写法,笔记中有1种写法) 1.聚 ...
- docker postgres
启动一个 Postgres 实例 docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d daocloud.i ...
- linux下安装mysql问题总结(一)mysqld_safe mysqld from pid file /usr/local/mysql/data/mysql.pid ended
linux下安装mysql数据库 linux版本:CentOS release 6.8 (Final) mysql版本:mysql-5.7.16-linux-glibc2.5-x86_64.tar.g ...