How to forward a REST request to another resource?

前端 未结 1 1367
再見小時候
再見小時候 2021-02-09 08:08

In my current architecture, I have a JAX-RS resource that sits behind:

/categories
/categories/{catId}

that\'s implemented like this:



        
1条回答
  •  鱼传尺愫
    2021-02-09 08:30

    For this you can use Sub-resource locators, which is basically a method in the resource class that returns another resource class. The thing about the examples in the link is that they instantiate the resource class themselves, for example

    @Path("/item")
    public class ItemResource {
        @Path("content")
        public ItemContentResource getItemContentResource() {
            return new ItemContentResource();
        }
    }
    
    public class ItemContentResource {
        @PUT
        @Path("{version}")
        public void put(@PathParam("version") int version)
        }
    }
    

    which works, but I am not sure if it preserves injections, for instance if you wanted to inject @Context UriInfo into a field in ItemContentResource. It should work though if you injected into the method param instead.

    To get around this, there is the ResourceContext, which when used, should preserve all the injections. For example in your current case, you can do

    @Path("/categories")
    @Produces("application/json")
    public static class CategoryResourcesApi {
    
        @Context
        private ResourceContext resourceContext;
    
        @Path("/{catId}/products")
        public ProductResourcesApi getProducts() {
            return resourceContext.getResource(ProductResourcesApi.class);
        }
    }
    
    @Path("/products")
    @Produces("application/json")
    public static class ProductResourcesApi {
    
        @Context
        private UriInfo info;
    
        @GET
        @Path("/{id}")
        public Response getProducts(
                @PathParam("id") String prodId,
                @PathParam("catId") String catId) {
        }
    }
    

    The getProducts would map to the URI /categories/{catId}/products/{prodId}. You just need to check if the catId is null (only if you need it to do any lookup) I guess to determine if the request is a request to the root products resource or to the parent categories resource. Small price to pay for code reuse I guess.

    And just looking at your comment, I believe in the past Swagger didn't support sub-resource locators, but I believe now they do. You may want to search around for any discussions if you have problems with it. Here's a discussion, and another one, and another one

    0 讨论(0)
提交回复
热议问题