问题
I have a query parameter as following:
@GET
public Response myFunction(@QueryParam("start") final LocalDate start, @QueryParam("end") final LocalDate end) { ... }
For this, I created a ParamConverter<LocalDate>
which converts a string to a date, and vice versa.
Now I want to use @DefaultValue
annotation to declare a default value. I have two special default values:
- today (for
start
) - the maximum value/infinity (for
end
)
Is it possible to use the @DefaultValue
annotation for this? How?
回答1:
Yes, @DefaultValue value can be used in this situation:
@GET
public Response foo(@QueryParam("start") @DefaultValue("today") LocalDate start,
@QueryParam("end") @DefaultValue("max") LocalDate end) {
...
}
Your ParamConverterProvider and ParamConverter implementations can be like:
@Provider
public class LocalDateParamConverterProvider implements ParamConverterProvider {
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType,
Annotation[] annotations) {
if (rawType.getName().equals(LocalDate.class.getName())) {
return new ParamConverter<T>() {
@Override
public T fromString(String value) {
return parseString(value, rawType);
}
@Override
public String toString(T value) {
return ((LocalDateTime) value)
.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
};
}
return null;
}
private <T> T parseString(String value, Class<T> rawType) {
if (value == null) {
return null;
}
if ("today".equalsIgnoreCase(value)) {
return rawType.cast(LocalDate.now());
}
if ("max".equalsIgnoreCase(value)) {
return rawType.cast(LocalDate.of(9999, 12, 31));
}
try {
return rawType.cast(LocalDate.parse(value,
DateTimeFormatter.ISO_LOCAL_DATE));
} catch (Exception e) {
throw new BadRequestException(e);
}
}
}
If, for some reason, you need the parameter name, you can get it from the Annotation
array:
Optional<Annotation> optional = Arrays.stream(annotations)
.filter(annotation -> annotation.annotationType().equals(QueryParam.class))
.findFirst();
if (optional.isPresent()) {
QueryParam queryParam = (QueryParam) optional.get();
String parameterName = queryParam.value();
}
来源:https://stackoverflow.com/questions/48114283/defaultvalue-in-jax-rs-for-dates-now-and-max