SpringBoot-javax.validation

2020-05-02  本文已影响0人  张明学

说明

本篇主要介绍javax的validation使用,以实际使用出发,后续会再更新,先记录一部分。

简介

javax的validation是基于标准JSR-303规范。JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。

JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation,Hibernate Validator 是 Bean Validation 的参考实现 . Hibernate Validator 提供了 JSR 303 规范中所有内置 constraint 的实现,除此之外还有一些附加的 constraint。JSR-303参考

在SpringBoot中使用方法


 <!-- Validation 相关依赖 -->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.1.Final</version>
    </dependency>

由于SpringBoot中spring-boot-starter-web中引用了hibernate-validator、hibernate-validator又引用了validation-api。因此不需要额外引用validation-api

public class UserReq implements Serializable {
    /**
     * 任意类型,验证注解的元素值不是null
     */
    @NotNull(message = "userName不能为空")
    private String userName;

    /**
     * BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存储的是数字)子类型
     *
     * @Min验证注解的元素值大于等于@Min指定的value值,
     * @Max验证注解的元素值小于等于@Max指定的value值
     */
    @Min(value = 18, message = "不能小于18岁")
    @Max(value = 60, message = "不能大于60岁")
    @NotNull
    private Integer userAge;

    /**
     * @Past必须是过去的一个时间
     * @Future必须是将来的一个时间
     */
    @Past(message = "birthday")
    @DateTimeFormat(pattern = "yyy-MM-dd")
    @JSONField(format = "yyyy-MM-dd")
    private Date birthday;

    /**
     * 字符串、Collection、Map、数组等。验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小
     */
    @Size(min = 1, max = 3, message = "联系人信息不能为空")
    private List<ContactInfo> contactInfo;
}
@PostMapping("/user")
    public String addUser(@RequestBody @Validated UserReq userReq) {
        log.info("保存User={}", JSON.toJSONString(userReq));
        return "SUCCESS";
    }

异常的捕捉。SpringBoot-异常处理

@ExceptionHandler({
            MethodArgumentNotValidException.class,
            BindException.class,
            ValidationException.class,
            ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse tryValidationException(HttpServletRequest request, HandlerMethod handlerMethod, Exception e) {
        log.error("参数校验异常,url={},{}#{}", request.getRequestURL(), handlerMethod.getClass(), handlerMethod.getMethod().getName(), e);
        BindingResult result = null;
        if (e instanceof MethodArgumentNotValidException) {
            result = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : result.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        if (errorMsg.length() > 1) {
            errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        }
        return new BaseResponse().setCode("30").setMessage(errorMsg.toString());
    }

约束注解


其中:@NotEmpty、@Length、@Range、@Email 是Hibernate Validator附加的。

上一篇 下一篇

猜你喜欢

热点阅读