廖师兄源码: https://gitee.com/liaoshixiong/girl
样例:拦截所有未满18岁的女生
第一步:在girl实体类中:添加注解 @Min(value=18 ,message = "未成年少女禁止入内!")
package com.payease.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.Min; /** * Created by liuxiaoming on 2017/11/6. */ @Entity public class Girl { @Id @GeneratedValue private int id; private String cupSize; @Min(value=18 ,message = "未成年少女禁止入内!") private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCupSize() { return cupSize; } public void setCupSize(String cupSize) { this.cupSize = cupSize; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
第二步:GirlResposity
package com.payease.respository; import com.payease.domain.Girl; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by liuxiaoming on 2017/11/6. */ public interface GirlRespository extends JpaRepository<Girl,Integer>{ }
第三步:在controller 中 添加注解:@Valid
@Autowired private GirlRespository girlRespository; /** * 创建一个女生 */ @PostMapping("/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 girlRespository.save(girl); }
第四步:postman提交