如何从CXF REST服务类获取上下文路径

时间:2015-05-14 20:48:35

标签: java tomcat cxf jax-rs war

我有一个在Tomcat中运行的WAR文件。此WAR包含许多html页面(用于测试目的)http://localhost:port/testapp/somepage.html

此应用程序中还包含一个CXF REST服务端点,该端点位于http://localhost:port/testapp/cxf/,并提供一些服务,例如http://localhost:port/testapp/cxf/getlink

getlink方法服务应返回指向其中一个html页面的链接。 我不想在代码或配置文件中静态设置上下文路径,因为我无法控制应用程序将托管在哪个上下文路径。

所以我想要做的是在运行时获取上下文路径。我该怎么做?

我尝试了以下内容(注意@Path("/")" cxf"路径的一部分来自web.xml,它是CXF servlet路径)

@Path("/")
public class TestEndpoint {
...
@Context
UriInfo uri;

@GET
@Path("/getlink")
public Response giveMeXML(@Context Request context) {
    URI baseURI = UriBuilder.fromUri(uri.getBaseUri()).replacePath("").build();
....
}

我希望UriInfo.getBaseUri()给我一个包含" scheme:// host:port / contextpath"的URI。我的申请,但它没有。它回来了 "方案://主机:端口/ contextPath中/ CXF-APP-路径"比如http://localhost:8080/testapp/cxf

如何在REST端点中获取部署WAR的上下文路径?我们想要的是以某种方式获得部署WAR的上下文路径,例如:http://localhost:8080/testapp/

1 个答案:

答案 0 :(得分:1)

不幸的是,AFAICT,没有单一的API来获取这些信息。您需要手动执行它(使用一些字符串操作)。一种方法是注入HttpServletRequest并使用 API来创建路径。例如

@GET
public String getServletContextPath(@Context HttpServletRequest request) {
    return getAbsoluteContextPath(request);
}

public String getAbsoluteContextPath(HttpServletRequest request) {
    String requestUri = request.getRequestURL().toString();
    int endIndex = requestUri.indexOf(request.getContextPath()) 
                                    + request.getContextPath().length();
    return requestUri.substring(0, endIndex); 
}
相关问题