如何使用 JAX-RS 获取根上下文 url?
How can I get root-context url with JAX-RS?
给定的应用程序
@ApplicationPath("/api")
public class MyApplication {
}
UriInfo#getBaseUri给我一个申请路径。
@Context
private UriInfo uriInfo
uriInfo.getBaseUri(); // http://address/<context-path>/api
如何获取上下文路径?
如何获得完整的 URL 上下文路径?
http://address/<context-path>
更新
我目前使用的代码来自 this answer。
@Context
private HttpServletRequest servletRequest;
final URI contextUri
= URI.create(servletRequest.getRequestURL().toString())
.resolve(servletRequest.getContextPath());
还有其他建议吗?
要获取应用程序上下文,您可以在 REST 方法中注入 ServletContext 并从中检索 contextPath,例如:
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Catalog find(@PathParam("id") Long id, @Context ServletContext servletContext) {
String contextPath = servletContext.getContextPath();
...
}
编辑
得到你想要的"full URL to context-path"。您还可以使用 @Context 注释注入 HttpServletRequest 并使用 getScheme()、getServerName() 和 getServerPort() 种构建方法。
一种可能的方法是使用 HttpServletRequest
.
@Context
private HttpServletRequest servletRequest;
final URI contextUri
= URI.create(servletRequest.getRequestURL().toString())
.resolve(servletRequest.getContextPath());
给定的应用程序
@ApplicationPath("/api")
public class MyApplication {
}
UriInfo#getBaseUri给我一个申请路径。
@Context
private UriInfo uriInfo
uriInfo.getBaseUri(); // http://address/<context-path>/api
如何获取上下文路径?
如何获得完整的 URL 上下文路径?
http://address/<context-path>
更新
我目前使用的代码来自 this answer。
@Context
private HttpServletRequest servletRequest;
final URI contextUri
= URI.create(servletRequest.getRequestURL().toString())
.resolve(servletRequest.getContextPath());
还有其他建议吗?
要获取应用程序上下文,您可以在 REST 方法中注入 ServletContext 并从中检索 contextPath,例如:
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Catalog find(@PathParam("id") Long id, @Context ServletContext servletContext) {
String contextPath = servletContext.getContextPath();
...
}
编辑
得到你想要的"full URL to context-path"。您还可以使用 @Context 注释注入 HttpServletRequest 并使用 getScheme()、getServerName() 和 getServerPort() 种构建方法。
一种可能的方法是使用 HttpServletRequest
.
@Context
private HttpServletRequest servletRequest;
final URI contextUri
= URI.create(servletRequest.getRequestURL().toString())
.resolve(servletRequest.getContextPath());