1 package com.ieou.comac.module.web.dto.employee; 2 3 import lombok.Data; 4 5 import javax.validation.constraints.NotBlank; 6 import javax.validation.constraints.NotEmpty; 7 import javax.validation.constraints.Pattern; 8 9 /** 10 * created by wyz on 2019/4/19 11 */ 12 @Data 13 public class EmployeeReq { 14 15 16 @NotEmpty(message = "請選擇員工類型") 17 private String employeesType; 18 19 @NotEmpty(message = "請輸入員工姓名") 20 private String name; 21 22 @NotEmpty(message = "請輸入IC卡號") 23 private String icNo; 24 25 @NotEmpty(message = "請輸入聯系電話") 26 private String mobilePhone; 27 28 }
// controller層 方法參數中加@Valid注解
1 /** 2 * created by wyz on 2019/4/19 3 */ 4 @RestController 5 @RequestMapping("/web/employee") 6 public class EmployeeController { 7 8 @Autowired 9 private EmployeeService employeeService; 10 11 12 @PostMapping("/addEmployee") 13 public void createEmployee(@Valid @RequestBody EmployeeReq employeeReq, BindingResult bindingResult) throws Exception { 14 Util.checkBindingResult(bindingResult); 15 employeeService.createEmployee(employeeReq); 16 } 17 18 }
//3.工具類
1 public class Util { 2 3 /** 4 * 驗證是否有異常 5 * 6 * @param bindingResult 參數驗證結果 7 * @throws Exception 直接拋出異常 8 */ 9 public static void checkBindingResult(BindingResult bindingResult) throws Exception { 10 if (bindingResult == null) { 11 return; 12 } 13 if (bindingResult.hasErrors()) { 14 String errorMessage = bindingResult.getAllErrors().get(0).getDefaultMessage(); 15 if (errorMessage != null && errorMessage.length() > 50) { 16 errorMessage = "參數錯誤"; 17 } 18 throw new ComacException(errorMessage); 19 } 20 } 21 }
4.JSR303定義的校驗類型
1 空檢查 2 @Null 驗證對象是否為null 3 @NotNull 驗證對象是否不為null, 無法查檢長度為0的字符串 4 @NotBlank 檢查約束字符串是不是Null還有被Trim的長度是否大於0,只對字符串,且會去掉前后空格. 5 @NotEmpty 檢查約束元素是否為NULL或者是EMPTY. 6 7 Booelan檢查 8 @AssertTrue 驗證 Boolean 對象是否為 true 9 @AssertFalse 驗證 Boolean 對象是否為 false 10 11 長度檢查 12 @Size(min=, max=) 驗證對象(Array,Collection,Map,String)長度是否在給定的范圍之內 13 @Length(min=, max=) Validates that the annotated string is between min and max included. 14 15 日期檢查 16 @Past 驗證 Date 和 Calendar 對象是否在當前時間之前 17 @Future 驗證 Date 和 Calendar 對象是否在當前時間之后 18 @Pattern 驗證 String 對象是否符合正則表達式的規則 19 20 數值檢查,建議使用在Stirng,Integer類型,不建議使用在int類型上,因為表單值為“”時無法轉換為int,但可以轉換為Stirng為"",Integer為null 21 @Min 驗證 Number 和 String 對象是否大等於指定的值 22 @Max 驗證 Number 和 String 對象是否小等於指定的值 23 @DecimalMax 被標注的值必須不大於約束中指定的最大值. 這個約束的參數是一個通過BigDecimal定義的最大值的字符串表示.小數存在精度 24 @DecimalMin 被標注的值必須不小於約束中指定的最小值. 這個約束的參數是一個通過BigDecimal定義的最小值的字符串表示.小數存在精度 25 @Digits 驗證 Number 和 String 的構成是否合法 26 @Digits(integer=,fraction=) 驗證字符串是否是符合指定格式的數字,interger指定整數精度,fraction指定小數精度。 27 28 @Range(min=, max=) 檢查數字是否介於min和max之間. 29 @Range(min=10000,max=50000,message="range.bean.wage") 30 private BigDecimal wage; 31 32 @Valid 遞歸的對關聯對象進行校驗, 如果關聯對象是個集合或者數組,那么對其中的元素進行遞歸校驗,如果是一個map,則對其中的值部分進行校驗.(是否進行遞歸驗證) 33 @CreditCardNumber信用卡驗證 34 @Email 驗證是否是郵件地址,如果為null,不進行驗證,算通過驗證。 35 @ScriptAssert(lang= ,script=, alias=) 36 @URL(protocol=,host=, port=,regexp=, flags=)