@Valid 对表单进行验证
程序员文章站
2023-12-21 16:28:46
...
在学到springBoot的课程中遇到了使用@Valid进行表单验证
controller
//@Valid Girl girl :需要进行验证的类
//BindingResult 验证之后返回的对象
@PostMapping(value = "/girls")
public Object girlAdd(@Valid Girl girl, BindingResult bindingResult){
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return bindingResult.getFieldError().getDefaultMessage();
}
girl.setAge(girl.getAge());
girl.setCupSize(girl.getCupSize());
return girlRespository.save(girl);
}
实体类:
package com.winter.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;
/**
* Created by Administrator on 2017/7/4.
*/
@Entity()
public class Girl {
@Id
@GeneratedValue
private Integer id;
private String cupSize;
//需要在这个类中使用验证的注解,除了这个还有@notNull....等等
@Min(value=18, message = "未成年人请勿入内")
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;
}
}