JAX-RS 2.0资源实例构建时的应用程序上下文路径 [英] Application context path at JAX-RS 2.0 resource instance construction
问题描述
是否有可能在JAX-RS 2.0资源类实例构造时(以及可能在静态类初始化时)获得Java EE 7应用程序的上下文路径,还是仅在向端点中的端点请求时才可用?资源类别?
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?
通过上下文路径,我是指Java EE 7应用程序中对HttpServletRequest#getContextPath()
的调用将返回的字符串.
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.
但是,我并不关心请求的URL中实际使用的上下文路径.适用于该类端点的规范或默认上下文路径对我来说已经足够了.
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.
获取这种上下文路径的技术不必特定于JAX-RS 2.0.只要它可以在JAX-RS 2.0资源类构建时(或更广泛地说,在静态类初始化时)运行,它就可以来自其他Java EE 7规范.
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).
更新:
我忘了提到该类是CDI @ApplicationScoped
,因此在请求时不调用其构造函数,就像在@RequestScoped
时那样.
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
.
推荐答案
您可以通过将UriInfo
注入资源的构造函数中来获取REST应用程序的基本URI:
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(){
...
}
}
大多数UriInfo
方法将在资源构造时返回IllegalStateException
,但是getBaseUri()
方法将起作用.
Most of the UriInfo
methods will return IllegalStateException
at resource construction time, but the getBaseUri()
method will work.
它将返回类似http://<hostname>:<port>/<context-path>/<base-path>
的URI.
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...
这篇关于JAX-RS 2.0资源实例构建时的应用程序上下文路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!