Use annotations check

BindingResult annotation using the entity class verification Implementation Notes

First, the introduction of validatorjar packet, and adds parity annotation on the entity class field to be verified

The need to introduce the hibernate org.hibernate.validator, in springboot2.x using javax.validation then add the following comments on the verification entity class field to be verified:


@Entity
@Table(name="sys_goods")
public class GoodsInfo extends BaseModel {
    @Id
    @GeneratedValue
    private long goodsNo;
    @NotBlank
    private String goodsName;
    @NotBlank
    private String manufacturer;        //生产厂家
    @NotBlank
    private String specifications;      //包装规格
    @NotNull
    private BigDecimal price;           //价格
    @NotBlank
    private boolean beactive;           //是否活动

    public long getGoodsNo() {
        return goodsNo;
    }

    public void setGoodsNo(long goodsNo) {
        this.goodsNo = goodsNo;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getSpecifications() {
        return specifications;
    }

    public void setSpecifications(String specifications) {
        this.specifications = specifications;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public boolean isBeactive() {
        return beactive;
    }

    public void setBeactive(boolean beactive) {
        this.beactive = beactive;
    }
}

Attach a common check notes:

@Null       验证对象是否为null

@NotNull     验证对象是否不为null, 无法查检长度为0的字符串

@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.

@NotEmpty 检查约束元素是否为NULL或者是EMPTY.

Booelan检查

@AssertTrue     验证 Boolean 对象是否为 true  

@AssertFalse    验证 Boolean 对象是否为 false  

长度检查

@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内

@Length(min=, max=) 验证字符串的长度是否在给定的范围之内,包含两端

日期检查

@Past        验证 Date 和 Calendar 对象是否在当前时间之前

@Future     验证 Date 和 Calendar 对象是否在当前时间之后

@Pattern    验证 String 对象是否符合正则表达式的规则

数值检查:建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null

@Min            验证 Number 和 String 对象是否大等于指定的值  

@Max            验证 Number 和 String 对象是否小等于指定的值  

@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度

@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度

@Digits     验证 Number 和 String 的构成是否合法  

@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。


@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.

@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;

@Valid递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)

@CreditCardNumber信用卡验证

@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。

@ScriptAssert(lang= ,script=, alias=)

@URL(protocol=,host=, port=,regexp=, flags=)

Second, increasing the associated parity check code is required in the controller

Use example:

 @PostMapping("/dbinfo")
    public @ResponseBody  ResponseEntity<BaseResponse<DbInfo>>  save(@Validated @RequestBody DbInfo newDbInfo, BindingResult bindingResult)
    {
        ResponseEntity<BaseResponse<DbInfo>> response=null;
        BaseResponse<DbInfo> baseResponse=null;
        if(bindingResult.hasErrors())
        {
            StringBuilder sb=new StringBuilder();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                sb.append(fieldError.getDefaultMessage());
                sb.append(" ");
            }
            //提示错误信息
            baseResponse=new BaseResponse<>();
            baseResponse.setCode(400);
            baseResponse.setMessage(sb.toString());
            response=new  ResponseEntity<BaseResponse<DbInfo>>(baseResponse, HttpStatus.BAD_REQUEST);
        }
        else
        {
//            进行保存
            DbInfo savedResult = dbInfoRepository.save(newDbInfo);
            baseResponse=new BaseResponse<>();
            baseResponse.setData(savedResult);
            baseResponse.setCode(200);
            baseResponse.setMessage("保存成功");
            response=new  ResponseEntity<BaseResponse<DbInfo>>(baseResponse, HttpStatus.OK);
        }
        return  response;
    }

Guess you like

Origin www.cnblogs.com/falcon-fei/p/11060134.html