程序化Jersey资源中的路径参数 [英] Path parameter in programmatic Jersey resource
问题描述
我正在使用此处在运行时从配置文件动态创建配置的资源. 我创建这些资源的代码如下:
I am using Jersey's programmatic API described here to dynamically create configured resources from a configuration file at runtime. My code to create those resources follows these lines:
public ResourceCreator() {
for (String resource : cfg.getConfiguredResources())
{
logger.log(Level.CONFIG, "Creating resource {0}", resource);
final Resource.Builder resourceBuilder = Resource.builder()
.path(resource);
resourceBuilder.addMethod("GET")
.produces(MediaType.APPLICATION_JSON_TYPE)
.handledBy(new Inflector<ContainerRequestContext, Response>() {
@Override
public Response apply(ContainerRequestContext rctx) {
// Create response here
}
});
final Resource resourceObj = resourceBuilder.build();
registerResources(resourceObj);
}
}
这很好,但是下一步是以编程方式为子资源(子资源?)提供Path参数.通常我会用
This works fine, however the next step is to programmatically provide subresources (child resources?) with a Path parameter. Normally I would annotate these with
@GET
@Path( "/{id}" )
@Produces( { "application/json" } )
public Response processIdGet( @PathParam( "id" ) String id ...)
现在-我如何以编程方式执行此操作?
至少可以说,关于程序化API的Jersey文档非常简洁.
The Jersey documentation regarding the programmatic API is very concise to say the least.
推荐答案
问了问题之后,您知道如何开始看到解决方案吗?
Do you know how you start seeing the solution after you've asked the question?
事实证明,我必须以与@Path
批注相同的方式添加带有 path 的子资源.之后,我可以通过上下文的getUriInfo()
方法获得path参数.
It turns out I have to add a child resource with a path in the same manner as the @Path
annotation. After that, I can get at the path parameter through the getUriInfo()
method of the context.
像这样:
final Resource.Builder subResourceBuilder = resourceBuilder.addChildResource("{id}");
subResourceBuilder.addMethod("GET")
.produces(MediaType.APPLICATION_JSON_TYPE)
.handledBy(new Inflector<ContainerRequestContext, Response>() {
@Override
public Response apply(ContainerRequestContext rctx) {
// Get to the path parameter
MultivaluedMap<String, String> pparams = rctx.getUriInfo().getPathParameters();
List<String> idValues = pparams.get("id");
// Create response here
}
});
这篇关于程序化Jersey资源中的路径参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!