【问题标题】:How do i get the context path from a CXF REST service class如何从 CXF REST 服务类获取上下文路径
【发布时间】:2015-05-15 17:28:20
【问题描述】:

我有一个在 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 servlets 路径)

@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,但它没有。它返回 "scheme://host:port/contextpath/cxf-app-path" 比如http://localhost:8080/testapp/cxf

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

【问题讨论】:

    标签: java tomcat cxf jax-rs war


    【解决方案1】:

    很遗憾,AFAICT,没有单一的 API 可以获取此信息。您将需要手动完成(通过一些字符串操作)。一种方法是注入HttpServletRequest 并使用its 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); 
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多