使用自定义验证验证REST端点参数与LocalDate
问题描述:
我使用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
。我不确定在这里做什么。有什么建议么?