首页 > 技术文章 > Java SpringBoot 实体类数据自动验证

smartsmile 2019-10-05 21:36 原文

package demo.dto;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotEmpty;
import java.io.Serializable;

public class ProductDto implements Serializable {
    @NotEmpty(message = "姓名 不允许为空")
    @Length(min = 2, max = 10, message = "姓名 长度必须在 {min} - {max} 之间")
    private String userName;

    @NotEmpty(message = "密码 不允许为空")
    private String password;

    @NotEmpty(message = "真实姓名 不允许为空")
    private String realName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName == null ? null : realName.trim();
    }
    /**
     *
     @NotEmpty,@NotNull和@NotBlank的区别
     1 @NotEmpty :不能为null,且Size>0

     2 @NotNull:不能为null,但可以为empty,没有Size的约束

     3 @NotBlank:只用于String,不能为null且trim()之后size>0
     *
     @NotNull
     使用该注解的字段的值不能为null,否则验证无法通过。

     @Null
     修饰的字段在验证时必须是null,否则验证无法通过。

     @Size
     如下代码表示,修饰的字段长度不能超过5或者低于。

     @Size(min = 1, max = 5)
     private String name;
     1
     2
     @Max
     如下代码表示,该字段的最大值为19,否则无法通过验证。
     @Max(value = 19)
     private Integer age;
     1
     2
     @Min
     同理,被该注解修饰的字段的最小值,不能低于某个值。

     @AssertFalse
     该字段值为false时,验证才能通过。

     @AssertTrue
     该字段值为true时,验证才能通过。

     @DecimalMax
     验证小数的最大值。

     @DecimalMax(value = "12.35")
     private double money;
     1
     2
     @DecimalMin
     验证小数的最小值。

     @Digits
     验证数字的整数位和小数位的位数是否超过指定的长度。

     @Digits(integer = 2, fraction = 2)
     private double money;
     1
     2
     @Future
     验证日期是否在当前时间之后,否则无法通过校验。
     @Future
     private Date date;
     1
     2
     @Past
     验证日期是否在当前时间之前,否则无法通过校验。

     @Pattern
     用于验证字段是否与给定的正则相匹配。

     @Pattern(regexp = "[abc]")
     private String name;
     */

}

  

package demo.entity;

import java.io.Serializable;

public class Product implements Serializable {
    private Integer id;

    private String userName;

    private String password;

    private String realName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }


    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName == null ? null : realName.trim();
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", username='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", realname='" + realName + '\'' +
                '}';
    }
}
   //添加数据
    @RequestMapping("/addproduct")
    public Object addproduct(@Valid ProductDto model, BindingResult result) {
        int errorCount = result.getErrorCount();
        MessagePack messagePack = new MessagePack();
        // 验证字段是否符合规则
        if (result.hasErrors()) {
            throw new RuntimeException(result.getFieldError().getDefaultMessage());
        } else {
            Product product = new Product();
            BeanUtils.copyProperties(model, product);
            // 操作数据
            int i = Convert.toInt(productService.addProduct(product));
            // 判断操作成功与否
            if (i > 0) {
                messagePack.setCode(0);
                messagePack.setMessage("新增商品成功");
                messagePack.setObject(null);
                messagePack.setStatus("OK");
            } else {
                messagePack.setCode(-1);
                messagePack.setMessage("新增商品失败");
                messagePack.setObject(null);
                messagePack.setStatus("error");
            }
        }
        return messagePack;
    }

 

推荐阅读