title: How can you build an absolute URL in thymeleaf?
body: <p>I would like to display an absolute url generated at run-time with a parameter. Not create a href to a page but display the URL using <code>th:text</code>. Any simple way to do this with Tymeleaf (without having to concatenate the URL pieces from #request object and without using some MVC utility class)?</p>
  
  <p><strong>Attempt 1</strong></p>
  
  <p><code>&lt;p th:text="@{/myServlet(myParam=${dynamicParameter})}" /&gt;</code> - only displays part of the URL leaving out the protocol, port and host name. I am getting <code>/myServlet?myParam=123</code>. The same behavior as for <code>th:href</code>, if you inspect the <code>&lt;a&gt;</code> you will see the same href - in that case the browser helps by inferring the protocol, port and so on</p>
  
  <p><strong>Attempt 2</strong></p>
  
  <p><code>th:text="@{__${#httpServletRequest.requestURI}__}"</code> - produces a relative URI of the current page that doesn't include the protocol and so on</p>
  
  <p><strong>Attempt 3</strong></p>
  
  <p><code>th:text="@{__${#httpServletRequest.requestURL}__}"</code> - produces this time an absolute URL of the current page containing the protocol, host and servlet context. The problem now is when I display this text from a different page, my URL is <code>...myApp/myOtherServlet</code> so I need to edit this string to replace <code>myOtherServlet</code> with the URI I want.</p>
  
  <p><strong>Non Tymeleaf Attempt 1</strong></p>
  
  <pre><code>@Service("urlUtils")
  public class UrlUtilsServiceImpl implements UrlUtilsService {
  @Override
      public String getAbsoluteUrlTo(final String aPath, final String param, final String value){
          return ServletUriComponentsBuilder
                  .fromCurrentContextPath()
                  .path(aPath)
                  .queryParam(param, value)
                  .build().toString();
      }
  }
  </code></pre>
  
  <p>page.html:</p>
  
  <pre><code>th:text="${@urlUtils.getAbsoluteUrlTo('/myServlet', 'myParam', ${dynamicParameter})}"
  </code></pre>
  
  <p>The problem is the host name that can be aliased before it reaches my server (see <a href="https://stackoverflow.com/questions/21482093/how-to-get-the-server-name-in-a-java-web-application">this</a>).
  <strong>Thymeleaf+JS Sollution</strong></p>
  
  <p>Using some java script plus thymeleaf</p>
  
  <pre><code>&lt;p id="myUrl" th:text="@{/myServlet(myParam=${dynamicParameter})}" /&gt;
  &lt;script type="text/javascript"&gt;
      $(document).ready(function () {
          var myUrl= $("#myUrl");
          myUrl.text(window.location.origin + myUrl.text());
          });
  &lt;/script&gt;
  </code></pre>