2015-01-12
9:54 AM
有用Spring MVC的都知道使用@Valid註解的方便性
但Spring本身支援的驗證服務僅僅只有基本的功能
因此若有一些較複雜的驗證就必須自行實作
若善用此功能將會使程式碼顯得更優雅
以下將以檢查List是否為空作範例實作此功能
程式碼範例
//首先需定義驗證用的Annotation
@Documented
@Constraint(validatedBy = ListNotEmptyValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface ListNotEmpty {
String message() default "Empty list";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
//接著定義Validator
public class ListNotEmptyValidator implements ConstraintValidator<ListNotEmpty, List<?>> {
@Override
public void initialize(ListNotEmpty constraintAnnotation) {
}
// 在此定義驗證方法
@Override
public boolean isValid(List<?> value, ConstraintValidatorContext context) {
if( value == null || value.isEmpty() ) return false;
return true;
}
}
就這麼簡單
其實就是定義一個Annotation + 驗證用的class即可
詳細解說
// 此class內我們最常使用到的會是 message 欄位
// 但Spring預設將會使用到這三種欄位 因此必須加入
@Documented
@Constraint(validatedBy = ListNotEmptyValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface ListNotEmpty {
// 驗證錯誤時回傳的訊息 default 後接預設字串
String message() default "Empty list";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
/*
@Documented - 是否再使用此Annotation的物件文件上顯示此Annotation,若使用Eclipse產生文件似乎沒有影響
不論是否使用皆會顯示
@Constraint - 用來作為驗證的class,此class必須 implement javax.validation.ConstraintValidator
@Target - 此Annotation可以用在何處,如欄位、方法等等,以此例來說,
若將此Annotation加在class上會顯示錯誤
@Retention - SOURCE: annotation retained only in the source file and
is discarded during compilation.
CLASS: annotation stored in the .class file during compilation,
not available in the run time.
RUNTIME: annotation stored in the .class file and available in the run time.
They are defined java.lang.annotation.RetentionPolicy enumeration.
*/
/*
此class必須實作ConstraintValidator
第一個型態為驗證用Annotation 第二個型態為驗證對象的型態
接著只要在 isValid 方法內撰寫驗證方法即可
若驗證錯誤則回傳false 驗證正確則回傳true
而驗證錯誤時將會自動套用加入Annotation時傳入的message參數
*/
public class ListNotEmptyValidator implements ConstraintValidator<ListNotEmpty, List<?>> {
@Override
public void initialize(ListNotEmpty constraintAnnotation) {
}
@Override
public boolean isValid(List<?> value, ConstraintValidatorContext context) {
if( value == null || value.isEmpty() ) return false;
return true;
}
}
各項資料連結
Getting Started · Validating Form Input - Spring
No comments:
Post a Comment