【发布时间】:2012-11-20 21:56:40
【问题描述】:
我想在 Jersey 中使用 Joda 的 DateTime 查询参数,但 Jersey 开箱即用不支持此功能。我假设实现InjectableProvider 是添加DateTime 支持的正确方法。
有人能指出我对DateTime 的InjectableProvider 的良好实现吗?或者有没有值得推荐的替代方法? (我知道我可以在我的代码中从 Date 或 String 转换,但这似乎是一个较小的解决方案。
谢谢。
解决方案:
我在下面修改了 Gili 的答案,以使用 JAX-RS 中的 @Context 注入机制而不是 Guice。
更新:如果 UriInfo 未注入您的服务方法参数,这可能无法正常工作。
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import java.util.List;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;
/**
* Enables DateTime to be used as a QueryParam.
* <p/>
* @author Gili Tzabari
*/
@Provider
public class DateTimeInjector extends PerRequestTypeInjectableProvider<QueryParam, DateTime>
{
private final UriInfo uriInfo;
/**
* Creates a new DateTimeInjector.
* <p/>
* @param uriInfo an instance of {@link UriInfo}
*/
public DateTimeInjector( @Context UriInfo uriInfo)
{
super(DateTime.class);
this.uriInfo = uriInfo;
}
@Override
public Injectable<DateTime> getInjectable(final ComponentContext cc, final QueryParam a)
{
return new Injectable<DateTime>()
{
@Override
public DateTime getValue()
{
final List<String> values = uriInfo.getQueryParameters().get(a.value());
if( values == null || values.isEmpty())
return null;
if (values.size() > 1)
{
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).
entity(a.value() + " may only contain a single value").build());
}
return new DateTime(values.get(0));
}
};
}
}
【问题讨论】:
标签: java jersey jax-rs jodatime