我正在使用 Jersey: 1.17.1 并定义了一个接受“application/x-www-form-urlencoded”的 REST 服务。我想接受 ISO-8601 格式的参数“b”,并让 Jersey 将其映射到 Joda DateTime。
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createTask(@FormParam("a") String a, @FormParam("b") DateTime b) {
...
但我得到了这个例外
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public de.ast.mae.rest.util.response.Response de.ast.mae.rest.service.tasks.TasksAdminRestService.createTask(java.lang.String,org.joda.time.DateTime) at parameter at index 6
SEVERE: Missing dependency for method public de.ast.mae.rest.util.response.Response de.ast.mae.rest.service.tasks.TasksAdminRestService.createTask(java.lang.String,org.joda.time.DateTime) at parameter at index 6
SEVERE: Method, public de.ast.mae.rest.util.response.Response de.ast.mae.rest.service.tasks.TasksAdminRestService.createTask(java.lang.String,java.lang.String,org.joda.time.DateTime), annotated with PUT of resource, class de.ast.mae.rest.service.tasks.TasksAdminRestService, is not recognized as valid resource method.
Okt 09, 2013 5:54:41 PM com.sun.jersey.spi.spring.container.servlet.SpringServlet initiate
SEVERE: Exception occurred when intialization
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
我需要做什么才能完成这项工作?
答案是:我先升级到 JAX-RS 2.0,然后使用:
@Provider
public class DateTimeParamConverterProvider implements ParamConverterProvider {
@Override
public <T> ParamConverter<T> getConverter(Class<T> type, Type genericType, Annotation[] annotations) {
if (type.equals(DateTime.class)) {
return (ParamConverter<T>) new DateTimeParamConverter();
} else {
return null;
}
}
private static class DateTimeParamConverter implements ParamConverter<DateTime> {
@Override
public DateTime fromString(String value) {
try {
return ISODateTimeFormat.dateTimeNoMillis().parseDateTime(value);
} catch (IllegalArgumentException e) {
return ISODateTimeFormat.dateTime().parseDateTime(value);
}
}
@Override
public String toString(DateTime value) {
return value.toString();
}
}
}