2011-03-01 36 views

回答

13

您可以從FacesContext得到ExternalContext,並從外部環境抽取request然後

String file = request.getRequestURI(); 
if (request.getQueryString() != null) { 
    file += '?' + request.getQueryString(); 
} 
URL reconstructedURL = new URL(request.getScheme(), 
           request.getServerName(), 
           request.getServerPort(), 
           file); 
reconstructedURL.toString(); 

source

2

讓我重新短語Jigar的回答有點:

final ExternalContext ectx = context.getExternalContext(); 
String url = ectx.getRequestScheme() 
    + "://" + ectx.getRequestServerName() 
    + ":" + ectx.getRequestServerPort() 
    + "/" + ectx.getRequestContextPath(); 
16

一個更簡潔的方法是:

HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); 
String url = request.getRequestURL().toString(); 
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/"; 

那麼你不需要用省略端口撥弄時,方案是http和端口是80等。

+0

在這種情況下,我們也失去了「上下文路徑」 – yegor256

+0

對不起,你的問題並沒有掩蓋它。只需添加'+ request.getContextPath()'。我會更新答案。 – BalusC

+0

我認爲,這裏'request.getRequestURI()。substring(0)','.substring(0)'不是必需的。是否需要一些非常特殊的情況? – Tiny

7

這是我發現的最簡單的方法,它不涉及URL各個部分的神祕字符串處理。它似乎適用於所有情況,包括不同的協議和端口。

String getAbsoluteApplicationUrl() throws URISyntaxException { 
     ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); 
     HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); 
     URI uri = new URI(request.getRequestURL().toString()); 
     newUri = new URI(uri.getScheme(), null, 
       uri.getHost(), 
       uri.getPort(), 
       request.getContextPath().toString(),null, null); 
     return newUri.toString(); 
} 
3

我有一個類似BalusC的:

FacesContext context = FacesContext.getCurrentInstance(); 
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest(); 
String requestURL = request.getRequestURL().toString(); 
String url = requestURL.substring(0, requestURL.lastIndexOf("/")); 
相關問題