[英]How to get an absolute URL of webapp from ExternalContext?
A more concise way is: 更简洁的方法是:
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String url = request.getRequestURL().toString();
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
Then you don't need to fiddle with omitting the ports when the scheme is http
and port is 80
and so on. 然后,当方案为
http
且端口为80
时,您不需要忽略端口,依此类推。
You can get ExternalContext
from FacesContext
and extract request
from External context then 您可以从
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();
This is the easiest way I've found that doesn't involve mysterious string manipulation on the various parts of the URL. 这是我发现的最简单的方法,它不涉及URL的各个部分的神秘字符串操作。 It seems to work in all cases, including different protocols and ports.
它似乎适用于所有情况,包括不同的协议和端口。
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();
}
I have one similar to BalusC's: 我有一个类似于BalusC的:
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
String requestURL = request.getRequestURL().toString();
String url = requestURL.substring(0, requestURL.lastIndexOf("/"));
Let me re-phrase Jigar's answer a bit: 让我重新说一下Jigar的答案:
final ExternalContext ectx = context.getExternalContext();
String url = ectx.getRequestScheme()
+ "://" + ectx.getRequestServerName()
+ ":" + ectx.getRequestServerPort()
+ "/" + ectx.getRequestContextPath();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.