开发者

How to get an absolute URL of webapp from ExternalContext?

开发者 https://www.devze.com 2023-02-14 06:29 出处:网络
I\'m trying to retrieve the root URL of a web application from ExternalContext, but can\'t u开发者_开发问答nderstand which method to use...A more concise way is:

I'm trying to retrieve the root URL of a web application from ExternalContext, but can't u开发者_开发问答nderstand which method to use...


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.


You can get ExternalContext from FacesContext and extract request from External context then

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


This is the easiest way I've found that doesn't involve mysterious string manipulation on the various parts of the 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:

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:

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

精彩评论

暂无评论...
验证码 换一张
取 消