@Validated :綁定須要校驗的數據.html
數據校驗規則:爲數據綁定校驗的規則前端
private Long booId;
@NotNull(message = "不能爲空")
private String bookName;
private String author;
private String publisher;
@DecimalMin(value = "20",message = "不能低於20元")
@DecimalMax(value = "100",message = "不能多於100")
private Float price;
//正則表達式檢驗
//正則表達式用來判斷某個字符串是否符合某個規則
//或者用來提取一整個字符 串中知足某個規則的子串
@Pattern(regexp = "1[345678][0-9]{9}")
private String Mobile;
爲是實體類屬性綁定檢驗規則:
message爲檢驗不合格時的提示信息.
import javax.validation.constraints.*; public class BookBean { private Long booId; @NotNull(message = "書名不能爲空") private String bookName; private String author; private String publisher; @DecimalMin(value = "20",message = "不能低於20元") @NotNull(message = "價格不能爲空") @DecimalMax(value = "100",message = "不能多於100") private Float price; //正則表達式檢驗 //正則表達式用來判斷某個字符串是否符合某個規則 //或者用來提取一整個字符 串中知足某個規則的子串 @Pattern(regexp = "1[345678][0-9]{9}") private String Mobile;public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getMobile() { return Mobile; } public void setMobile(String mobile) { Mobile = mobile; } public Long getBooId() { return booId; } public void setBooId(Long booId) { this.booId = booId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } }
綁定數據檢驗:java
注意:校驗結果:BindingResult result必須經跟在@Validated BokBean bokBean 後面.用於接受檢驗的結果.正則表達式
@RequestMapping("/book/creat") public String create(@Validated BokBean bokBean, BindingResult result, Model model){ //能夠經過BindingResult對象拿到校驗的錯誤信息. //注意:該參數必需要緊跟在被校驗的對象的後面 if (result.hasErrors()){ //判斷是否有檢驗的錯誤 // result.getFieldError("bookName").getDefaultMessage(); for (FieldError error : result.getFieldErrors()) { //獲取被校驗對象的全部錯誤 String message = error.getDefaultMessage(); System.out.println(message); } //能夠直接把錯誤信息的集合都放到集合裏 model.addAttribute("erros", result.getFieldErrors()); return "erro"; } return "success"; }
自定義檢驗規則,有時候spring自帶的檢驗規則不知足咱們使用時,能夠自定義檢驗規則.spring
檢驗規則:app
public class IDValidator implements ConstraintValidator<IDVlidation,String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { //這裏引用了一個身份證檢驗的工具類 return IdCardUtils.isIDCard(value); }
//這個方法可不實現 @Override public void initialize(IDVlidation constraintAnnotation) { } }
自定義一個檢驗規則的註解,自定義註解見自定義註解章節:https://www.cnblogs.com/zhouchangyang/p/10908343.htmlide
定義這個註解爲了方便,可仿造spring定義的註解規則寫(賦值粘貼)工具
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) //代表該註解可用在哪裏 @Retention(RUNTIME) //代表生效時間 @Repeatable(IDVlidation.List.class) @Constraint(validatedBy = {IDValidator.class}) //註明該註解所實現的規則是哪一個類 public @interface IDVlidation { String message() default ""; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @interface List { IDVlidation[] value(); } }
這樣就定義好了一個規則的註解,this
使用自定義註解和使用系統的註解同樣,添加到須要校驗的屬性上面便可:spa
@IDVlidation(message = "省份證不符合規範") private String idCard;
獲取校驗的後不知足規則的錯誤信息方式有兩種:
一種就像上面同樣在 方法參數中檢驗的對象後面添加 BindingResult result,
@RequestMapping("/book/creat") public String create(@Validated BokBean bokBean, BindingResult result, Model model){
第二種是單獨寫一個獲取錯誤信息的方法,在方法上添加註解,@ExceptionHandler(BindException.class),
經過 BindException ex 同樣能得到第一種方法的BindingResult 對象.對錯誤信息的進一步操做和第一種方法同樣.
@ExceptionHandler(BindException.class) public String resolveBindinngExcrption(BindException ex){ //獲取錯誤結果集. BindingResult result = ex.getBindingResult(); FieldError error = ex.getFieldError(); System.out.println(result); return "erro"; }
分組校驗:
某些時候,咱們前端的某些請求須要對某個對象的一部分屬性進行校驗,有一部分屬性不須要校驗.
這時咱們就須要對校驗的屬性進行分組,根據前端的需求對屬性進行分類.
好比登陸和註冊業務,他們引用的都是用戶對象,可是登陸只須要校驗用戶名和密碼,而註冊除了校驗登陸和註冊還須要校驗不少數據,
假如規定了註冊時手機號不能爲空,在登錄時不須要手機號,就會報錯,這時就須要用分組來針對性的校驗.
建立一個實體類,並對屬性添加校驗規則和分組信息,
public class UserBean { //登陸分組 public interface LoginGroup{} //註冊分組 public interface RegisterGroup{} @NotBlank(message = "不能爲空",groups = {LoginGroup.class,RegisterGroup.class}) private String username; @JsonIgnore //表示不想序列化的數據 @NotBlank(groups = {LoginGroup.class,RegisterGroup.class}) private String password; @Pattern(message = "手機號錯誤",regexp = "1[3-9][\\d]{9}",groups = {RegisterGroup.class}) @NotNull(message = "手機號不能爲空",groups = {RegisterGroup.class}) private String mobile; @AssertTrue(groups = {RegisterGroup.class}) private boolean agree; @JsonFormat(pattern = "yyyy-MM-dd-HH:mm:ss",timezone = "GMT+8") private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public boolean isAgree() { return agree; } public void setAgree(boolean agree) { this.agree = agree; } }
分組校驗用法:
在實體類中建立內部接口類(能夠是普通類),用來對業務進行分類,
public class UserBean { //登陸分組 public interface LoginGroup{} //註冊分組 public interface RegisterGroup{}
在屬性的檢驗規則中添加分組屬性 :
@NotBlank(message = "不能爲空",groups = {LoginGroup.class,RegisterGroup.class})
表示這個不能爲空的檢驗規則登陸和註冊都須要知足.
//登陸分組 public interface LoginGroup{} //註冊分組 public interface RegisterGroup{} @NotBlank(message = "不能爲空",groups = {LoginGroup.class,RegisterGroup.class}) private String username; @JsonIgnore //表示不想序列化的數據 @NotBlank(groups = {LoginGroup.class,RegisterGroup.class}) private String password; @Pattern(message = "手機號錯誤",regexp = "1[3-9][\\d]{9}",groups = {RegisterGroup.class}) @NotNull(message = "手機號不能爲空",groups = {RegisterGroup.class}) private String mobile; @AssertTrue(message = "必須爲真",groups = {RegisterGroup.class}) private boolean agree;
規定好校驗規則和分組後,只需在須要校驗的地方使用就能夠,
用法:在方法參數檢驗標記中添加分組屬性:@Validated(UserBean.LoginGroup.class)
表示只有被UserBean.LoginGroup.class分組的校驗規則纔會被列入本次校驗
@Controller public class UserController { @RequestMapping("/login") public String login(@Validated(UserBean.LoginGroup.class) UserBean userBean){ return "success"; } @RequestMapping("/register") public String register(@Validated(UserBean.RegisterGroup.class) UserBean userBean){ return "success"; }
原文出處:https://www.cnblogs.com/zhouchangyang/p/10914528.html