Springboot集成Validator

目录

1. Validator使用概述

2. Validator使用案例

2.1 数据库准备

2.2 核心代码

2.3 案例测试


1. Validator使用概述

通常来说一个api开放的参数都需要做验证,在开发期间也遇到一些问题,所以以下作出一些总结分享。

常用的单数据源源码可以参考:springboot-jpa-demo(spring-hibernate-validator)

以下源码会放在spring-jpa-multiple-datasources分支。

数据库使用的是postgres。

2. Validator使用案例

2.1 数据库准备

1) 当前db是public,有一张userinfo表。

 2) public.userinfo数据。

2.2 核心代码

1) 实体类。

@Data
public class UserInfoDTO {

    @NotBlank(message = "name can not null")
    @Length(max = 20, message = "name can not exceed 20 characters")
    @Pattern(regexp = "^[\\u4E00-\\u9FA5A-Za-z0-9\\*]*$", message = "no more than 10 characters,including text, letters, and numbers.")
    @JsonProperty(value = "name")
    private String name;

    @NotBlank(message = "gender can not null")
    @JsonProperty(value = "gender")
    private String gender;

    @NotNull(message = "age can not empty")
    @Min(value = 1, message = "age should be between 1 and 120")
    @Max(value = 120, message = "age should be between 1 and 120")
    @JsonProperty(value = "age")
    private int age;

    @NotNull(message = "futureDate can not empty")
    @Future(message = "futureDate is invalid")
    @JsonProperty(value = "futureDate")
    private Date futureDate;

    @NotNull(message = "birthDate can not empty")
    @Past(message = "birthDate is invalid")
    @JsonProperty(value = "birthDate")
    private Date birthDate;
}

:如果需要对字段进行验证却不生效,加上@NotNull。  

 2) 全局异常处理器。

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * After the parameter verification fails, MethodArgumentNotValidException will be thrown.
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringJoiner sj = new StringJoiner(";");
        e.getBindingResult().getFieldErrors() // get all the errors
                .forEach(x -> sj.add(x.getDefaultMessage()));

        Map map = new HashMap<>();
        map.put("code", UUID.randomUUID());
        map.put("msg", sj.toString());
        return map;
    }

    /**
     * After the parameter verification fails, ConstraintViolationException will be thrown.
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Map handleConstraintViolationException(ConstraintViolationException e) {
        StringJoiner sj = new StringJoiner(";");
        e.getConstraintViolations().forEach(x -> sj.add(x.getMessage()));
        Map map = new HashMap<>();
        map.put("code", 1001);
        map.put("msg", sj.toString());

        return map;
    }

}

2.3 案例测试

如果已经安装了postman可以直接用:

{
    "name": "123123",
    "age": 1,
    "gender": "female",
    "birthDate": "2000-04-23",
    "futureDate": "2022-05-23"
}

或者用:postman脚本

1) 正常通过验证。

 更新后的userInfo表。

 2) 验证失败。

附:

1) 如果需要验证的属性带有嵌套层级,可以将@Valid用在嵌套层级的成员属性上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值