如何从外部上下文获取web应用程序的绝对URL?

2022-09-03 16:58:59

我正在尝试从外部上下文检索Web应用程序的根URL,但无法理解使用哪种方法...


答案 1

更简洁的方法是:

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

然后,您无需在方案是和端口等情况下省略端口。http80


答案 2

您可以从外部上下文获取和提取,然后ExternalContextFacesContextrequest

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


推荐