【SpringBoot基础】使用validation注解对入参进行校验

1. 不优雅的参数校验

后端对前端传过来的参数是需要进行校验的,如果在controller中直接校验需要用大量的if else做判断。以添加用户的接口为例,需要对前端传过来的参数进行校验, 如下的校验就是不优雅的:

@PostMapping("add")
    public ResponseEntity<String> add(User user) {
        if(user.getName()==null) {
            return ResponseResult.fail("user name should not be empty");
        } else if(user.getName().length()<5 || user.getName().length()>50){
            return ResponseResult.fail("user name length should between 5-50");
        }
        if(user.getAge()< 1 || user.getAge()> 150) {
            return ResponseResult.fail("invalid age");
        }
        // ...
        return ResponseEntity.ok("success");
    }

2. Validation 中的常见constraint

@DecimalMax(value):被注解的元素必须为一个数字,其值必须小于等于指定的最小值
@DecimalMin(Value):被注解的元素必须为一个数字,其值必须大于等于指定的最小值
@Digits(integer=, fraction=):被注解的元素必须为一个数字,其值必须在可接受的范围内
@Email:被注释的元素必须是电子邮箱
@Future:被注解的元素必须是日期,必须是将来日期
@Past:被注解的元素必须是日期,必须是过去日期
@Max(value):被注解的元素必须为一个数字,其值必须小于等于指定的最大值
@Min(value):被注解的元素必须为一个数字,其值必须大于等于指定的最小值
@NotNull:被注解的元素必须不为null
@NotBlank:CharSequence子类型,验证注解的元素值不为空(包括不为null或去除首尾空格后长度为0)
@NotEmpty:被注释的对象必须不为空(数据:String,Collection,Map,arrays)
@Size(min=, max=):被注解的元素必须在制定的范围(对象、数组或集合的大小)
@Pattern(regex=, flag=):被注解的元素必须符合正则表达式

3. 举例:请求参数封装并添加validation注解约束和message

将查询用户的参数封装到UserParam中, 而不是User(数据库实体)本身。

public class UserParam implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotEmpty(message = "could not be empty")
    private String userId;

    @NotEmpty(message = "could not be empty")
    @Email(message = "invalid email")
    private String email;

    @NotEmpty(message = "could not be empty")
    @Pattern(regexp = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$", message = "invalid ID")
    private String cardNo;

    @NotEmpty(message = "could not be empty")
    @Length(min = 1, max = 10, message = "nick name should be 1-10")
    private String nickName;

    @NotEmpty(message = "could not be empty")
    @Range(min = 0, max = 1, message = "sex should be 0-1")
    private int sex;

    @Max(value = 100, message = "Please input valid age")
    private int age;

    @Valid
    private AddressParam address;

}

4. controller层使用参数校验

使用@Valid或者@Validated注解。

@PostMapping("add")
    public ResponseEntity<String> add(@Valid @RequestBody UserParam userParam)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天`南

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值