Spring Boot - 3

数据验证

1、在属性上添加验证条件

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;

@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;
    
    @Min(value = 18,message = "未成年少禁止入内")  //数据合法性验证
    private Integer age;

    private String cupSize;

    public Girl() {
    }

    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }
}

2、数据自动注入用@Valid开启验证

/**
     * 添加一个Girl
     * @return
     */

    @PostMapping(value = "/girls")
    public Girl grilAdd(@Valid Girl girl, BindingResult bindingResult){  //@Valid开启数据验证,BindingResult获得验证结果
        if(bindingResult.hasErrors()){
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }

        return girlRepository.save(girl);
    }

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×