无尽光芒

JSR303介绍和使用

2022.05.20

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

<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.16.Final</version>
</dependency>

Bean Validation 中内置的 constraint

image.png

Hibernate Validator 附加的 constraint

image.png


public class UmsAdminParam {

    //规定长度
    @Length(min = 6, max = 19, message = "用户名长度是6-18位")
    @ApiModelProperty(value = "用户名", required = true)
    private String username;

    @ApiModelProperty(value = "密码", required = true)
    private String password;

    //不能是空的
    @NotEmpty
    @ApiModelProperty(value = "用户头像")
    private String icon;

    @Email(message = "邮箱格式错误")
    @ApiModelProperty(value = "邮箱")
    private String email;

    @NotNull
    @ApiModelProperty(value = "用户昵称")
    private String nickName;

    @ApiModelProperty(value = "备注")
    private String note;
}

@Valid 通知Spring 校验

    public ResponseBo a(@Valid @RequestBody User user){
        return ResponseBo.ok(user);
    }

校验出异常:

org.springframework.web.bind.MethodArgumentNotValidException: 

Validation failed for argument [0] in public com.*.pojo.ResponseBo com.*.controller.TestController.a(com.*.pojo.User): 

[Field error in object 'user' on field 'goldCoin': 

rejected value [20000000]; 

codes [Digits.user.goldCoin,Digits.goldCoin,Digits.java.lang.Integer,Digits]; 

arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 

codes [user.goldCoin,goldCoin]; arguments []; default message [goldCoin],3,1]; 

default message [数字的值超出了允许范围(只允许在1位整数和3位小数范围内)]]