SpringBoot-表單驗(yàn)證
需求:添加一個(gè)女生肥惭,在提交表單時(shí)择克,年齡必須大于18
1.需要在對象的實(shí)體中加入注解@Min
2.需要在controller對應(yīng)的方法的參數(shù)中加入@Valid注解吞滞,標(biāo)明要驗(yàn)證的對象
3.驗(yàn)證的結(jié)果會返回到BindingResult對象中
例:
GirlController:
@RestController
public class GirlController {
@Autowired
private GirlRepository girlRepository;
@Autowired
private GirlService girlService;
@PostMapping(value="/girls")
public Girl girlAdd(@Valid Girl girl, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return null;
}
girl.setCupSize(girl.getCupSize());
girl.setAge(girl.getAge());
return girlRepository.save(girl);
}
}
Girl:
@Entity //該注解表示該類在數(shù)據(jù)庫中有對應(yīng)的表 不用創(chuàng)建該表
public class Girl {
@Id
@GeneratedValue
private Integer id;
private String cupSize;
/**
* 給年齡加上限制:年齡必須大于18歲
* value:值
* message:提示信息
*/
@Min(value =18,message = "年齡必須大于18歲")
private Integer age;
public Girl() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
GirlRepository:
public interface GirlRepository extends JpaRepository<Girl,Integer> {
/**JpaRepository<>
* 第一個(gè)參數(shù):類名
* 第二個(gè)參數(shù):id的類型
*/
//通過年齡來查詢
public List<Girl> findByAge(Integer age);
}
GirlApplication:
@SpringBootApplication
public class GirlApplication {
public static void main(String[] args) {
SpringApplication.run(GirlApplication.class, args);
}
}
application.yml:
spring:
profiles:
active: prod
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: 123456
jpa:
hibernate:
ddl-auto: create
show-sql: true