Search

Java - Spring MVC 的自定義 Validation

2015-01-12 9:54 AM

有用Spring MVC的都知道使用@Valid註解的方便性

但Spring本身支援的驗證服務僅僅只有基本的功能

因此若有一些較複雜的驗證就必須自行實作

若善用此功能將會使程式碼顯得更優雅

以下將以檢查List是否為空作範例實作此功能

程式碼範例
  1. //首先需定義驗證用的Annotation
  2. @Documented
  3. @Constraint(validatedBy = ListNotEmptyValidator.class)
  4. @Target( { ElementType.METHOD, ElementType.FIELD } )
  5. @Retention(RetentionPolicy.RUNTIME)
  6. public @interface ListNotEmpty {
  7. String message() default "Empty list";
  8. Class<?>[] groups() default {};
  9. Class<? extends Payload>[] payload() default {};
  10. }
  11.  
  12. //接著定義Validator
  13. public class ListNotEmptyValidator implements ConstraintValidator<ListNotEmpty, List<?>> {
  14.  
  15. @Override
  16. public void initialize(ListNotEmpty constraintAnnotation) {
  17. }
  18.  
  19. // 在此定義驗證方法
  20. @Override
  21. public boolean isValid(List<?> value, ConstraintValidatorContext context) {
  22. if( value == null || value.isEmpty() ) return false;
  23. return true;
  24. }
  25.  
  26. }

就這麼簡單

其實就是定義一個Annotation + 驗證用的class即可

詳細解說
  1. // 此class內我們最常使用到的會是 message 欄位
  2. // 但Spring預設將會使用到這三種欄位 因此必須加入
  3. @Documented
  4. @Constraint(validatedBy = ListNotEmptyValidator.class)
  5. @Target( { ElementType.METHOD, ElementType.FIELD } )
  6. @Retention(RetentionPolicy.RUNTIME)
  7. public @interface ListNotEmpty {
  8.  
  9. // 驗證錯誤時回傳的訊息 default 後接預設字串
  10. String message() default "Empty list";
  11. Class<?>[] groups() default {};
  12. Class<? extends Payload>[] payload() default {};
  13. }
  14.  
  15. /*
  16. @Documented - 是否再使用此Annotation的物件文件上顯示此Annotation,若使用Eclipse產生文件似乎沒有影響
  17. 不論是否使用皆會顯示
  18. @Constraint - 用來作為驗證的class,此class必須 implement javax.validation.ConstraintValidator
  19. @Target - 此Annotation可以用在何處,如欄位、方法等等,以此例來說,
  20. 若將此Annotation加在class上會顯示錯誤
  21. @Retention - SOURCE: annotation retained only in the source file and
  22. is discarded during compilation.
  23. CLASS: annotation stored in the .class file during compilation,
  24. not available in the run time.
  25. RUNTIME: annotation stored in the .class file and available in the run time.
  26. They are defined java.lang.annotation.RetentionPolicy enumeration.
  27. */
  28.  
  29. /*
  30. 此class必須實作ConstraintValidator
  31. 第一個型態為驗證用Annotation 第二個型態為驗證對象的型態
  32. 接著只要在 isValid 方法內撰寫驗證方法即可
  33. 若驗證錯誤則回傳false 驗證正確則回傳true
  34. 而驗證錯誤時將會自動套用加入Annotation時傳入的message參數
  35. */
  36. public class ListNotEmptyValidator implements ConstraintValidator<ListNotEmpty, List<?>> {
  37.  
  38. @Override
  39. public void initialize(ListNotEmpty constraintAnnotation) {
  40. }
  41.  
  42. @Override
  43. public boolean isValid(List<?> value, ConstraintValidatorContext context) {
  44. if( value == null || value.isEmpty() ) return false;
  45. return true;
  46. }
  47.  
  48. }
各項資料連結
Getting Started · Validating Form Input - Spring

No comments:

Post a Comment