问题
Is it possible to get the context path for a Java EE 7 application at JAX-RS 2.0 resource class instance construction time (and possibly at static class initialization time, too), or is it only available during requests to endpoints in the resource class?
By context path I mean the String that would be returned by a call to a HttpServletRequest#getContextPath()
within the Java EE 7 application.
I imagine that you probably could have multiple context path aliases for a deployed application. If so, context path might be available only at request time.
I don't care, however, about the context path that was actually used in the URL for the request. A canonical or default context path that will work for the endpoints in the class is good enough for me.
The technique to obtain such a context path need not be JAX-RS 2.0 specific. It could come from some other Java EE 7 spec, as long as it works at JAX-RS 2.0 resource class construction time (or, more broadly, at static class initialization time).
Update:
I forgot to mention that the class is CDI @ApplicationScoped
, so its constructor is not called at request time, as it would be if it were @RequestScoped
.
回答1:
You can get the base URI for your REST application by injecting UriInfo
in a resource's constructor:
@ApplicationScoped
@Path("/resourcePath")
public class MyRestResource {
public MyRestResource (@Context UriInfo uriInfo) {
URI uri = uriInfo.getBaseUri();
}
@GET
public Response someMethod(){
...
}
}
Most of the UriInfo
methods will return IllegalStateException
at resource construction time, but the getBaseUri()
method will work.
It will return an URI like http://<hostname>:<port>/<context-path>/<base-path>
.
But i'm not sure it would be possible to get it statically at class initialization time...
来源:https://stackoverflow.com/questions/26257028/application-context-path-at-jax-rs-2-0-resource-instance-construction