SpringBoot 使用validation数据校验
后端对数据进行验证
添加包
hibernate-validator
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0..Final</version>
</dependency>
或者添加spring-boot-starter-validation
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>1.4..RELEASE</version>
</dependency>
或者添加spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
这两个springboot包里面都包含hibernate-validator包,这三个包只有有一个就可以
二:返回信息
我这里通过抛出异常来统一返回异常信息
import com.shitou.huishi.contract.datacontract.code.RspCode;
import com.shitou.huishi.contract.datacontract.exception.AuthException;
import com.shitou.huishi.contract.datacontract.response.DataResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; /**
* Created by qhong on 2018/5/28 15:51
**/
@ControllerAdvice
public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(getClass()); /**
* 登陆异常
* @param req
* @param e
* @return
* @throws AuthException
*/
@ExceptionHandler(value = AuthException.class)
@ResponseBody
public DataResponse handleAuthException(HttpServletRequest req, AuthException e) throws AuthException {
DataResponse r = new DataResponse();
r.setResCode(e.getCode()+"");
r.setMsg(e.getMsg());
logger.info("AuthException",e.getMsg());
return r;
} /**
* 验证异常
* @param req
* @param e
* @return
* @throws MethodArgumentNotValidException
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody
public DataResponse handleMethodArgumentNotValidException(HttpServletRequest req, MethodArgumentNotValidException e) throws MethodArgumentNotValidException {
DataResponse r = new DataResponse();
BindingResult bindingResult = e.getBindingResult();
String errorMesssage = "Invalid Request:\n"; for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMesssage += fieldError.getDefaultMessage() + "\n";
}
r.setResCode(RspCode.VERIFICATION_DOES_NOT_PASS.getCode());
r.setMsg(errorMesssage);
logger.info("MethodArgumentNotValidException",e);
return r;
} /**
* 全局异常
* @param req
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public DataResponse handleException(HttpServletRequest req, Exception e) throws Exception {
DataResponse r = new DataResponse();
r.setResCode(RspCode.CODE_ERROR.getCode());
r.setMsg(RspCode.CODE_ERROR.getMessage()+","+e.getMessage());
logger.error(e.getMessage(),e);
return r;
}
}
三:具体代码
总结框架提供了那些校验:
JSR提供的校验注解:
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式 Hibernate Validator提供的校验注解:
@NotBlank(message =) 验证字符串非null,且trim后长度必须大于0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
Code:
@Range(min=,max=,message = "档案类型错误")
private Integer archiveType; @NotBlank(message = "档案主体名称不能为空")
private String subjectName; @NotBlank(message = "证件号不能为空")
private String subjectNo;
Controller:
public DataResponse createArchive(@RequestBody @Valid ArchiveInfoRequest request)
添加@Valid或者@Validated都可以。
补充:
网上提供的其他异常:
@ExceptionHandler(value =BindException.class)
@ResponseBody
public DataResponse handleBindException(BindException e) throws BindException {
// ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息,则调用ex.getAllErrors()
FieldError fieldError = e.getFieldError();
StringBuilder sb = new StringBuilder();
sb.append(fieldError.getField()).append("=[").append(fieldError.getRejectedValue()).append("]")
.append(fieldError.getDefaultMessage());
// 生成返回结果
DataResponse r = new DataResponse();
r.setResCode(RspCode.VERIFICATION_DOES_NOT_PASS.getCode());
r.setMsg(sb.toString());
logger.info("BindException", e);
return r;
}
https://blog.csdn.net/u013815546/article/details/77248003
https://blog.csdn.net/hry2015/article/details/79572713
SpringBoot 使用validation数据校验的更多相关文章
- SpringBoot中BeanValidation数据校验与优雅处理详解
目录 本篇要点 后端参数校验的必要性 不使用Validator的参数处理逻辑 Validator框架提供的便利 SpringBoot自动配置ValidationAutoConfiguration Va ...
- SpringBoot入门 (十一) 数据校验
本文记录学习在SpringBoot中做数据校验. 一 什么是数据校验 数据校验就是在应用程序中,对输入进来得数据做语义分析判断,阻挡不符合规则得数据,放行符合规则得数据,以确保被保存得数据符合我们得数 ...
- 1. 不吹不擂,第一篇就能提升你对Bean Validation数据校验的认知
乔丹是我听过的篮球之神,科比是我亲眼见过的篮球之神.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免 ...
- 【使用篇二】SpringBoot服务端数据校验(8)
对于任何一个应用而言,客户端做的数据有效性验证都不是安全有效的,而数据验证又是一个企业级项目架构上最为基础的功能模块,这时候就要求我们在服务端接收到数据的时候也对数据的有效性进行验证.为什么这么说呢? ...
- Springboot:JSR303数据校验(五)
@Validated //开启JSR303数据校验注解 校验规则如下: [一]空检查 @Null 验证对象是否为null @NotNull 验证对象是否不为null, 无法查检长度为0的字符串 @No ...
- SpringBoot 之 JSR303 数据校验
使用示例: @Component @ConfigurationProperties(prefix = "person") @Validated //使用数据校验注解 public ...
- SpringBoot - Bean validation 参数校验
目录 前言 常见注解 参数校验的应用 依赖 简单的参数校验示例 级联校验 @Validated 与 @Valid 自定义校验注解 前言 后台开发中对参数的校验是不可缺少的一个环节,为了解决如何优雅的对 ...
- 深入了解数据校验:Bean Validation 2.0(JSR380)
每篇一句 > 吾皇一日不退役,尔等都是臣子 对Spring感兴趣可扫码加入wx群:`Java高工.架构师3群`(文末有二维码) 前言 前几篇文章在讲Spring的数据绑定的时候,多次提到过数据校 ...
- 深入了解数据校验:Java Bean Validation 2.0(JSR380)
每篇一句 吾皇一日不退役,尔等都是臣子 相关阅读 [小家Java]深入了解数据校验(Bean Validation):基础类打点(ValidationProvider.ConstraintDescri ...
随机推荐
- shell文件的编写
见文章http://www.cnblogs.com/handsomecui/p/5869361.html
- python之mysqldb模块安装
之所以会写下这篇日志,是因为安装的过程有点虐心.目前这篇文章是针对windows操作系统上的mysqldb的安装.安装python的mysqldb模块,首先当然是找一些官方的网站去下载:https:/ ...
- yii2 rules验证规则,ajax验证手机号码是否唯一
<?php namespace frontend\models; use Yii; use yii\base\Model; /** * Signup form */ class SignupFo ...
- KL距离,Kullback-Leibler Divergence
http://www.cnblogs.com/ywl925/p/3554502.html http://www.cnblogs.com/hxsyl/p/4910218.html http://blog ...
- datetime处理日期和时间
datetime.now() # 获取当前datetimedatetime.utcnow() datetime(2017, 5, 23, 12, 20) # 用指定日期时间创建datetime 一.将 ...
- Java8函数式编程探秘
引子 将行为作为数据传递 怎样在一行代码里同时计算一个列表的和.最大值.最小值.平均值.元素个数.奇偶分组.指数.排序呢? 答案是思维反转!将行为作为数据传递. 文艺青年的代码如下所示: public ...
- JVM探秘4---垃圾收集器介绍
Java虚拟机有很多垃圾收集器 下面先来了解HotSpot虚拟机中的7种垃圾收集器:Serial.ParNew.Parallel Scavenge.Serial Old.Parallel Old.CM ...
- xshell中出现的绿色背景的文件夹
这种文件夹表示权限为777的文件夹 可以使用chmod 777 fileName进行权限修改 如果需要将文件夹以及其子文件夹的权限全部置为777 chmod 777 -R directoryName/ ...
- Lambda表达式select()和where()的区别
可能很多同学和我一样对于select()和where()区别并不是太清晰,其实两者还是有本质区别的. 1.where()用法:必须加条件,且返回对象结果. static void Main(strin ...
- .net core创建项目(指令方式)
所谓的指令创建项目,就是不用再已安装的VS2015的环境下或者VS Core下创建,直接通过DOS指令创建也是OK的. 1.找到你所准备保存项目的项目文件夹(你也可以到某个目录用指令创建项目文件夹[ ...