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;
2. Controller中开启验证
在Controller 中 请求参数上添加@Validated 标签开启验证
@RequestMapping(method = RequestMethod.POST) public User create(@RequestBody @Validated User user) { return userService.create(user); }
3. resource 下新建错误信息配置文件
在resource 目录下新建提示信息配置文件“ValidationMessages.properties“
注意:名字必须为“ValidationMessages.properties“ 因为SpringBoot自动读取classpath中的ValidationMessages.properties里的错误信息
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); } }
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,也可以通过正则表达式和flag指定自定义的email格式 |
示例
@Pattern(regexp="^[a-zA-Z0-9]+$",message="{account.username.space}")
@Size(min=3,max=20,message="{account.username.size}")

浙公网安备 33010602011771号