我正在尝试从ExternalContext检索Web应用程序的根URL,但无法理解使用哪种方法...
答案 0 :(得分:17)
更简洁的方法是:
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String url = request.getRequestURL().toString();
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
当方案为http
且端口为80
时,您不需要忽略端口等等。
答案 1 :(得分:13)
您可以从ExternalContext
获取FacesContext
并从外部上下文中提取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();
答案 2 :(得分: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 :(得分:3)
我有一个类似于BalusC的:
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
String requestURL = request.getRequestURL().toString();
String url = requestURL.substring(0, requestURL.lastIndexOf("/"));
答案 4 :(得分:2)
让我重新说一下Jigar的回答:
final ExternalContext ectx = context.getExternalContext();
String url = ectx.getRequestScheme()
+ "://" + ectx.getRequestServerName()
+ ":" + ectx.getRequestServerPort()
+ "/" + ectx.getRequestContextPath();