0

我使用Spring Boot構建了REST服務。在其中一個端點處,我有一個日期發佈了一個請求參數以及兩個其他參數。發佈後,請求參數綁定到一個對象。日期綁定在LocalDate字段中。發佈之後但在綁定之前,我喜歡使用驗證和Hibernate驗證器來驗證請求參數。 LocalDate沒有可用驗證,因此我需要爲LocalDate編寫自定義驗證。使用自定義驗證驗證REST端點參數與LocalDate

這是被髮布到端點:

/parameter-dates?parameterDateUnadjusted=2017-02-29&limit=5&direction=d 

這裏是端點代碼:

@GetMapping(value = "/parameter-dates") 
public ResponseEntity getParameterDates(@Valid ParameterDateRequest parameterDateRequest, Errors errors) { 
// DO SOME STUFF 
} 

這裏用於對象模型:

@Component 
@Data 
public class ParameterDateRequest { 

    @MyDateFormatCheck(pattern = "yyyy-MM-dd", message = "Date not matching") 
    LocalDate parameterDateUnadjusted; 
    @NotEmpty(message = "Direction can't be empty") 
    String direction; 
    @Digits(integer=1, fraction=0, message = "Limit has to be an integer of max 100 000") 
    int limit; 
} 

這是驗證註釋的代碼:

@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE }) 
@Retention(RUNTIME) 
@Constraint(validatedBy = MyDateFormatCheckValidator.class) 
@Documented 
public @interface MyDateFormatCheck { 
    String pattern(); 
    String message(); 

    Class<?>[] groups() default {}; 

    Class<? extends Payload>[] payload() default {}; 
} 

這對於驗證它自身的代碼:

public class MyDateFormatCheckValidator implements ConstraintValidator<MyDateFormatCheck, LocalDate> { 

    private MyDateFormatCheck check; 

    @Override 
    public void initialize(MyDateFormatCheck constraintAnnotation) { 
     this.check = constraintAnnotation; 
    } 

    @Override 
    public boolean isValid(LocalDate object, ConstraintValidatorContext constraintContext) { 
     if (object == null) { 
      return true; 
     } 

     return isValidDate(object, check.pattern()); 
    } 

    public static boolean isValidDate(LocalDate inDate, String format) { 
     // TEST IF inDate IS VALID RETURN TRUE/FALSE 
    } 
} 

這是錯誤的做法?我猜parameterDateUnadjusted實際上是一個String而不是LocalDate當它被髮布到端點,然後我的驗證器應該使用String作爲inDate但後來我需要將我的模型更改爲parameterDateUnadjusted爲字符串,它不適用於該程序因爲它使用它作爲LocalDate。我不確定在這裏做什麼。有什麼建議麼?

回答

0

我認爲你要找的是 - DateTimeFormat註釋。當數值已被綁定到LocalDate時,驗證日期格式沒有意義。