SpringBoot-表单验证
需求:添加一个女生,在提交表单时,年龄必须大于18
1.需要在对象的实体中加入注解@Min
2.需要在controller对应的方法的参数中加入@Valid注解,标明要验证的对象
3.验证的结果会返回到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 //该注解表示该类在数据库中有对应的表 不用创建该表
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<>
* 第一个参数:类名
* 第二个参数: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