spring注解式参数校验
很痛苦遇到大量的参数进行校验,在业务中还要抛出异常或者
返回异常时的校验信息,在代码中相当冗长,今天我们就来学习spring注解式参数校验.
其实就是:hibernate的validator.
开始啦......
1.controller的bean加上@Validated就像这样
@ApiOperation(value = "用户登录接口", notes = "用户登录")
@PostMapping("/userLogin")
public ResponseDTO<UserResponseDTO> userLogin(@RequestBody @Validated RequestDTO<UserLoginRequestDTO> requestDto) {
return userBizService.userLogin(requestDto);
}
2.下面是一些简单的例子:如在Bean中添加注解:
@Data
public class UserDTO implements Serializable {
private static final long serialVersionUID = -7839165682411118398L; @NotBlank(message = "用户名不能为空")
@Length(min=5, max=20, message="用户名长度必须在5-20之间")
@Pattern(regexp = "^[a-zA-Z_]\\w{4,19}$", message = "用户名必须以字母下划线开头,可由字母数字下划线组成")
private String username; @NotBlank(message = "密码不能为空")
@Length(min = 24, max = 44, message = "密码长度范围为6-18位")
private String password; @NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手机号不合法")
private String phone; @Email(message = "邮箱格式不正确")
private String email; @NotNull(message = "简介编号不能为空")
@NotEmpty(message = "简介编号不能为空")
private List<Integer> introList; @Range(min=0, max=4,message = "基础规格")
private int scale; @NotNull(message = "比例不能为空")
@DecimalMax(value = "100", message = "最大比率是100%啦~")
@DecimalMin(value = "0.01", message = "最小比率是0.01%啦~")
private Double cashbackRatio;
38 }
3.最后我们要进行切面配置,处理校验类的异常:
import com.cn.GateWayException;
import com.cn.alasga.common.core.dto.ResponseDTO;
import com.cn.ResponseCode;
import com.cn.alasga.common.core.exception.BizException;
import com.cn.TokenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.validation.ValidationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* @author Lijing
* @ClassName: ExceptionHandlerController.class
* @Description: 统一异常处理类
* @date 2017年8月9日 下午4:44:25
*/
@RestControllerAdvice
public class ExceptionHandlerController { private Logger log = LoggerFactory.getLogger(ExceptionHandlerController.class); private final static Pattern PATTERN = Pattern.compile("(\\[[^]]*])"); @ExceptionHandler(Exception.class)
public ResponseDTO handleException(Exception exception) { if (exception instanceof GateWayException) {
GateWayException gateWayException = (GateWayException) exception;
return new ResponseDTO<>(gateWayException);
} if (exception instanceof BizException) {
BizException biz = (BizException) exception;
return new ResponseDTO<>(biz);
} if (exception instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
return new ResponseDTO<>(methodArgumentNotValidException.getBindingResult().getFieldError()
.getDefaultMessage(), ResponseCode.PARAM_FAIL, ResponseDTO.RESPONSE_ID_PARAM_EXCEPTION_CODE);
} if (exception instanceof ValidationException) {
if (exception.getCause() instanceof TokenException) {
TokenException tokenException = (TokenException) exception.getCause();
return new ResponseDTO<>(tokenException);
}
} if (exception instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
return new ResponseDTO<>(ResponseCode.HTTP_REQUEST_METHOD_NOT_SUPPORTED);
} if (exception instanceof HttpMessageNotReadableException) {
log.error(exception.getMessage());
return new ResponseDTO<>(ResponseCode.HTTP_REQUEST_PARAMETER_INVALID_FORMAT);
} if (!StringUtils.isEmpty(exception.getMessage())) {
Matcher m = PATTERN.matcher(exception.getMessage());
if (m.find()) {
String[] rpcException = m.group(0).substring(1, m.group().length() - 1).split("-");
Integer code;
try {
code = Integer.parseInt(rpcException[0]);
} catch (Exception e) {
log.error(exception.getMessage(), exception);
return new ResponseDTO<>(ResponseDTO.RESPONSE_ID_BIZ_EXCEPTION_CODE, ResponseCode.RESPONSE_TIME_OUT);
}
return new ResponseDTO<>(ResponseDTO.RESPONSE_ID_BIZ_EXCEPTION_CODE, code, rpcException[1]);
}
} //主要输出不确定的异常
log.error(exception.getMessage(), exception); return new ResponseDTO<>(exception);
} }
MethodArgumentNotValidException 就是我们的 猪脚了 ,他负责获取这些参数校验中的异常,
ValidationException 是javax.的校验,和今天的校验也是有关系的,很久了,我都忘记验证了.

4.下面简单的解释一些常用的规则示意:
1.@NotNull:不能为null,但可以为empty(""," "," ")
2.@NotEmpty:不能为null,而且长度必须大于0 (" "," ")
3.@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0("test") 即:必须有实际字符
5.是不是很简单: 学会了就去点个赞
|
验证注解 |
验证的数据类型 |
说明 |
|
@AssertFalse |
Boolean,boolean |
验证注解的元素值是false |
|
@AssertTrue |
Boolean,boolean |
验证注解的元素值是true |
|
@NotNull |
任意类型 |
验证注解的元素值不是null |
|
@Null |
任意类型 |
验证注解的元素值是null |
|
@Min(value=值) |
BigDecimal,BigInteger, byte, short, int, long,等任何Number或CharSequence(存储的是数字)子类型 |
验证注解的元素值大于等于@Min指定的value值 |
|
@Max(value=值) |
和@Min要求一样 |
验证注解的元素值小于等于@Max指定的value值 |
|
@DecimalMin(value=值) |
和@Min要求一样 |
验证注解的元素值大于等于@ DecimalMin指定的value值 |
|
@DecimalMax(value=值) |
和@Min要求一样 |
验证注解的元素值小于等于@ DecimalMax指定的value值 |
|
@Digits(integer=整数位数, fraction=小数位数) |
和@Min要求一样 |
验证注解的元素值的整数位数和小数位数上限 |
|
@Size(min=下限, max=上限) |
字符串、Collection、Map、数组等 |
验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小 |
|
@Past |
java.util.Date, java.util.Calendar; Joda Time类库的日期类型 |
验证注解的元素值(日期类型)比当前时间早 |
|
@Future |
与@Past要求一样 |
验证注解的元素值(日期类型)比当前时间晚 |
|
@NotBlank |
CharSequence子类型 |
验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的首位空格 |
|
@Length(min=下限, max=上限) |
CharSequence子类型 |
验证注解的元素值长度在min和max区间内 |
|
@NotEmpty |
CharSequence子类型、Collection、Map、数组 |
验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) |
|
@Range(min=最小值, max=最大值) |
BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子类型和包装类型 |
验证注解的元素值在最小值和最大值之间 |
|
@Email(regexp=正则表达式, flag=标志的模式) |
CharSequence子类型(如String) |
验证注解的元素值是Email,也可以通过regexp和flag指定自定义的email格式 |
|
@Pattern(regexp=正则表达式, flag=标志的模式) |
String,任何CharSequence的子类型 |
验证注解的元素值与指定的正则表达式匹配 |
|
@Valid |
任何非原子类型 |
指定递归验证关联的对象; 如用户对象中有个地址对象属性,如果想在验证用户对象时一起验证地址对象的话,在地址对象上加@Valid注解即可级联验证 |
此处只列出Hibernate Validator提供的大部分验证约束注解,请参考hibernate validator官方文档了解其他验证约束注解和进行自定义的验证约束注解定义。
6.是不是很简单: 我再教你看源码:
ValidationMessages.properties 就是校验的message,就可以顺着看下去了!!!
7.补充 自定义注解
很简单 找源码抄一份注解 比如我们来个 自定义身份证校验 注解
来 注解走起
@Documented
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IdentityCardNumberValidator.class)
public @interface IdentityCardNumber { String message() default "身份证号码不合法"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};
}
再实现校验接口
public class IdentityCardNumberValidator implements ConstraintValidator<IdentityCardNumber, Object> {
@Override
public void initialize(IdentityCardNumber identityCardNumber) {
}
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
return IdCardValidatorUtils.isValidate18Idcard(o.toString());
}
}
最后 注解随便贴 IdCardValidatorUtils 是自己写的工具类 网上大把~ 需要的可以加我vx: cherry_D1314
如此便是完成了自定义注解,将统一异常处理即可.
spring注解式参数校验的更多相关文章
- spring注解式参数校验列表
校验注释列表: @AssertFalse Boolean,boolean 验证注解的元素值是false @AssertTrue Boolean,boolean 验证注解的元素值是true @NotNu ...
- 转 spring注解式参数校验
转自: https://blog.csdn.net/jinzhencs/article/details/51682830 转自: https://blog.csdn.net/zalan01408980 ...
- Spring基础系列-参数校验
原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9953744.html Spring中使用参数校验 概述 JSR 303中提出了Bea ...
- Spring注解式事务解析
#Spring注解式事务解析 增加一个Advisor 首先往Spring容器新增一个Advisor,BeanFactoryTransactionAttributeSourceAdvisor,它包含了T ...
- 【spring】-- jsr303参数校验器
一.为什么要进行参数校验? 当我们在服务端控制器接受前台数据时,肯定首先要对数据进行参数验证,判断参数是否为空?是否为电话号码?是否为邮箱格式?等等. 这里有个问题要注意: 前端代码一般上会对这些数据 ...
- Spring注解式与配置文件式
http://tom-seed.iteye.com/blog/1584632 Spring注解方式bean容器管理 1.通过在配置文件中配置spring组件注入 <context:compone ...
- SpringMVC学习笔记六:使用 hibernate-validator注解式数据校验
对客户端传过来的参数,在使用前一般需要进行校验. SpringMVC框架内置了Validator验证接口,但是实现起来太麻烦.我们一般使用 hibernate-validator进行数据校验. 1:j ...
- springmvc JSR303 Validate 注解式,校验数据
参考:http://www.cnblogs.com/liukemng/category/578644.html 先进行配置: <!-- 默认的注解映射的支持 --> <mvc:ann ...
- Spring注解式AOP面向切面编程.
1.AOP指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式.aop底层是动态代理. package com.bie.config; import org.aspectj.lan ...
随机推荐
- 《深度探索C++对象模型》读书笔记(一)
前言 今年中下旬就要找工作了,我计划从现在就开始准备一些面试中会问到的基础知识,包括C++.操作系统.计算机网络.算法和数据结构等.C++就先从这本<深度探索C++对象模型>开始.不同于& ...
- java.lang.Byte 类源码浅析
Byte 类字节,属于Number. public final class Byte extends Number implements Comparable<Byte> { /** * ...
- ngnix和负载均衡
1 准备环境 =====>part1: iptables -F #systemctl disable firewalld #开机默认关闭 #systemctl stop firewalld #立 ...
- spring整合thymeleaf
官方文档入口:https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html 1.首先需要引入thymeleaf的依赖(据官网文档,t ...
- 2018-2019-2 20165205 《网络对抗技术》 Exp1 PC平台逆向破解
2018-2019-2 20165205 <网络对抗技术> Exp1 PC平台逆向破解 1. 实验任务 1.1实验概括 用一个pwn1文件. 该程序正常执行流程是:main调用foo函数, ...
- 直达核心的快速学习PHP入门技巧
PHP(外文名:PHP: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言.语法吸收了C语言.Java和Perl的特点,利于学习,使用广泛,是目前最火的 ...
- HiveServer2的WEB UI界面
1.hive-site.xml配置如下: <property> <name>hive.server2.webui.host</name> <val ...
- 查询最新记录的sql语句效率对比
在工作中,我们经常需要检索出最新条数据,能够实现该功能的sql语句很多,下面列举三个进行效率对比 本次实验的数据表中有55万条数据,以myql为例: 方式1: SELECT * FROM t_devi ...
- 996 icu我能为你做什么?
今天996,未来icu 996icu地址:https://github.com/996icu/996.ICU 前段时间github上出现了,一个讨论996的项目,这个项目使中国的软件工程师达到了空前的 ...
- undefined symbol: PyFPE_jbuf
参考: https://blog.csdn.net/ture_dream/article/details/52733326 报错确实是Python的版本不一致. 但是我又不想删除anaconda. 怎 ...