问题
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);
}
}
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 ...)
now - how do I do this programmatically?
The Jersey documentation regarding the programmatic API is very concise to say the least.
回答1:
Do you know how you start seeing the solution after you've asked the question?
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.
Like this:
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
}
});
来源:https://stackoverflow.com/questions/47598437/path-parameter-in-programmatic-jersey-resource