Path parameter in programmatic Jersey resource

自闭症网瘾萝莉.ら 提交于 2019-12-11 09:46:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!