springboot 使用校验框架validation校验
b/s系统中对http请求数据的校验多数在客户端进行,这也是出于简单及用户体验性上考虑,但是在一些安全性要求高的系统中服务端校验是不可缺少的。
Spring3支持JSR-303验证框架,JSR-303 是Java EE 6 中的一项子规范,叫做BeanValidation,官方参考实现是hibernate Validator(与Hibernate ORM 没有关系),JSR 303 用于对Java Bean 中的字段的值进行验证。
validation与 springboot 结合
1. bean 中添加标签
部分代码:
标签需要加在属性上,@NotBlank 标签含义文章末尾有解释
public class User {
private Integer id;
@NotBlank(message = "{user.name.notBlank}")
private String name;
private String username;
1
2
3
4
5
2. Controller中开启验证
在Controller 中 请求参数上添加@Validated 标签开启验证
@RequestMapping(method = RequestMethod.POST)
public User create(@RequestBody @Validated User user) {
return userService.create(user);
}
1
2
3
4
3. resource 下新建错误信息配置文件
在resource 目录下新建提示信息配置文件“ValidationMessages.properties“
注意:名字必须为“ValidationMessages.properties“ 因为SpringBoot自动读取classpath中的ValidationMessages.properties里的错误信息
1
ValidationMessages.properties 文件的编码为ASCII。数据类型为 key value 。key“user.name.notBlank“为第一步 bean的标签 大括号里面对应message的值
value 为提示信息 ,但是是ASCII 。(内容为“名字不能为空“)
4. 自定义异常处理器,捕获错误信息
当验证不通过时会抛异常出来,异常的message 就是 ValidationMessages.properties 中配置的提示信息。此处定义异常处理器。捕获异常信息(因为验证不通过的项可能是多个所以统一捕获处理),并抛给前端。(此处是前后端分离开发)
public void MethodArgumentNotValidException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
logger.error( ":" + CommonUtil.getHttpClientInfo(request), ex);
MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex;
List<ObjectError> errors =c.getBindingResult().getAllErrors();
StringBuffer errorMsg=new StringBuffer();
errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
pouplateExceptionResponse(response, HttpStatus.INTERNAL_SERVER_ERROR, errorMsg.toString());
}
private void pouplateExceptionResponse(HttpServletResponse response, HttpStatus errorCode, String errorMessage) {
try {
response.sendError(errorCode.value(), errorMessage);
} catch (IOException e) {
logger.error("failed to populate response error", e);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
5. 附上部分标签含义
限制 说明
@Null 限制只能为null
@NotNull 限制必须不为null
@AssertFalse 限制必须为false
@AssertTrue 限制必须为true
@DecimalMax(value) 限制必须为一个不大于指定值的数字
@DecimalMin(value) 限制必须为一个不小于指定值的数字
@Digits(integer,fraction) 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
@Future 限制必须是一个将来的日期
@Max(value) 限制必须为一个不大于指定值的数字
@Min(value) 限制必须为一个不小于指定值的数字
@Past 限制必须是一个过去的日期
@Pattern(value) 限制必须符合指定的正则表达式
@Size(max,min) 限制字符长度必须在min到max之间
@Past 验证注解的元素值(日期类型)比当前时间早
@NotEmpty 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@NotBlank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
@Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式
示例
@Pattern(regexp="^[a-zA-Z0-9]+$",message="{account.username.space}")
@Size(min=3,max=20,message="{account.username.size}")
---------------------
作者:双斜杠少年
来源:CSDN
原文:https://blog.csdn.net/u012373815/article/details/72049796
版权声明:本文为博主原创文章,转载请附上博文链接!
阅读更多
- springboot 使用校验框架validation校验
- 使用SpringBoot通过自定义注解+AOP+全局异常处理实现参数统一非空校验
- Kotlin & Spring boot 使用@Valid校验无效解决方法
- springboot使用hibernate validator校验
- Spring boot 使用 shiro做安全校验
- 如何在Spring Boot项目使用参数校验
- Springboot 使用 JSR 303 对 Controller 控制层校验及 Service 服务层 AOP 校验 使用消息资源文件对消息国际化
- 关于怎么解决从ajax传入的json参数注入到Controller的接收对象 以及如何在Spring Boot项目使用参数校验
- Spring Boot项目使用参数校验
- 详解如何在Spring Boot项目使用参数校验
- springboot使用hibernate validator校验方式
- springboot使用hibernate validator校验
- 如何在Spring Boot项目使用参数校验
- SpringBoot 中使用声明式注解简化参数校验
- springboot使用Validator校验方式
- springboot使用hibernate validator校验方式
- springboot使用hibernate validator校验
- Spring boot redis的使用(二)
- SpringBoot中的拦截器的使用和配置
- SPRING BOOT:Hibernate实现的JPA中使用joda-time