Resolve what resource+method a URI would match in

2020-07-22 18:00发布

问题:

In our Jersey application we like to present/restrict different parts of our API based on roles. To be specific we would like to only offer links to resources which the role can visit - i.e. already when preparing response A we would not even offer a link to a resource X if the user would not be allowed to use X anyway.

To be able to distinguish those links we would like to be able to ask Jersey how it would resolve a certain URI - i.e. to what resource and to what method on that resource. If we could do that we would also be able to detect whether it is annotated in a way (@RolesAllowed) that would not permit access ... and hence we would be able to skip adding the link to the response in the making. Obviously Jersey has this knowledge/capabilities since it can resolve incoming requests.

The question is: Is there a way to ask Jersey what a URI would resolve to in terms of both class and method?

Edit: Yes ... we noticed there is a ResourceContext (which can be injected) which can provide us with the matching resource class ... but we still cannot find what method a URI would resolve to.

回答1:

Tobias,

ResourceContext.matchUriInfo(URI).getDeclaringResource() and ResourceContext.matchUriInfo(URI).getMatchedMethod().getMethod() will do what you're asking for.



回答2:

Interesting. I don't think this is a default service that is exposed, but assuming you're setting up jersey in web.xml your configuration is stored in WebServletConfig and ServletContainer. I'd take a look at the source for those two classes and see what's available. In the very least you should be able to subclass something in the stack that does the initialization and store the information you need yourself. It would be much more practical to get the mapping at the time when the classes are loaded and the annotation processing takes place rather than to look it up for each request.