簡體   English   中英

我如何從CXF REST服務類獲取上下文路徑

[英]How do i get the context path from a CXF REST service class

我有一個在Tomcat中運行的WAR文件。 此WAR包含http://localhost:port/testapp/somepage.html (出於測試目的)提供的許多html頁面。

此應用程序中還包括一個CXF REST服務終結點,該終結點托管在http://localhost:port/testapp/cxf/並帶有一些服務,例如http://localhost:port/testapp/cxf/getlink

getlink方法服務應返回到html頁面之一的鏈接。 我不想在代碼或配置文件中靜態設置上下文路徑,因為我無法控制將在何處托管應用程序的上下文路徑。

所以我想做的就是在運行時獲取上下文路徑。 我該怎么做呢?

我嘗試了以下操作(請注意,路徑的“ cxf”部分來自Web.xml,這是CXF servlet路徑,請注意@Path("/")

@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()給我一個URI,其中包含我應用程序的“ scheme:// host:port / contextpath”,但事實並非如此。 它會返回“ scheme:// host:port / contextpath / cxf-app-path”,例如http://localhost:8080/testapp/cxf

如何在REST端點中獲取WAR部署在其下的上下文路徑? 所需的是以某種方式獲取WAR部署在其下的上下文路徑,例如: http://localhost:8080/testapp/

不幸的是,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); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM