is it possible to call one jax-rs method from another?

后端 未结 2 577
死守一世寂寞
死守一世寂寞 2021-01-07 23:27

suppose i have some jax-rs resource class:

@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ResourceA {
   @GET
   pu         


        
相关标签:
2条回答
  • 2021-01-08 00:15

    You can get it using ResourceContext as follows:

    @Context 
    ResourceContext resourceContext;
    

    This will inject the ResourceContext into your Resource. You then get the resource you want using:

    ResourceB b = resourceContext.getResource(ResourceB.class);
    

    The Javadoc for ResourceContext is here. You can find a similar question here

    0 讨论(0)
  • 2021-01-08 00:17

    I'm not aware of any possibility to do this from a resource method, but if it fits your use case, what you could do is implement your redirect logic in a pre matching request filter, for example like so:

    @Provider
    @PreMatching
    public class RedirectFilter implements ContainerRequestFilter {
    
        @Override
        public void filter(ContainerRequestContext requestContext) {
            UriInfo uriInfo = requestContext.getUriInfo();
            String prefix = "/redirect";
            String path = uriInfo.getRequestUri().getPath();
            if (path.startsWith(prefix)) {
                String newPath = path.substring(prefix.length());
                URI newRequestURI = uriInfo.getBaseUriBuilder().path(newPath).build();
                requestContext.setRequestUri(newRequestURI);
            }
        }
    }
    

    This will redirect every request to /redirect/some/resource to /some/resource (or whatever you pass to requestContext.setRequestUri()) internally, before the resource method has been matched to the request and is executed and without http redirects or an additional internal http request.

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