title: Obtaining a URL up to the context path from the current HTTP request in JSF
body: <p>Assuming the following URL (with or without any query-string and/or extra path info).</p>
  
  <p><code>https://localhost:8181/ContextPath/xxx/page.xhtml</code></p>
  
  <p>Which I need to extract the following portion from.</p>
  
  <p><code>https://localhost:8181/ContextPath</code></p>
  
  <p>i.e. up to the context path.</p>
  
  <hr>
  
  <p>This can be done in one way defining a utility method of our interest something along the following piece of code.</p>
  
  <pre><code>public static String getBaseURL(HttpServletRequest request) {
      String url = request.getRequestURL().toString();
      return new String(url.substring(0, url.length() - request.getRequestURI().length())) + request.getContextPath();
  }
  </code></pre>
  
  <p>And it can be invoked from managed beans as follows.</p>
  
  <pre><code>HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
  String link=Utility.getBaseURL(request);
  </code></pre>
  
  <p>But this in turn requires exposing the underlying <code>javax.servlet.*</code> API which I am not interested in.</p>
  
  <p>Is there a sane JSF way in which the said portion of a URL from the current HTTP request can be obtained without explicitly exposing the underlying Servlet API?</p>
  
  <hr>
  
  <p><sup>I am not interested in individually collecting portions like scheme, server name, port, context path etc. using their respective separate methods associated with an instance of <code>HttpServletRequest</code>.</sup></p>