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 th:text
. 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)?
Attempt 1
<p th:text="@{/myServlet(myParam=${dynamicParameter})}" />
- only displays part of the URL leaving out the protocol, port and host name. I am getting /myServlet?myParam=123
. The same behavior as for th:href
, if you inspect the <a>
you will see the same href - in that case the browser helps by inferring the protocol, port and so on
Attempt 2
th:text="@{__${#httpServletRequest.requestURI}__}"
- produces a relative URI of the current page that doesn't include the protocol and so on
Attempt 3
th:text="@{__${#httpServletRequest.requestURL}__}"
- 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 ...myApp/myOtherServlet
so I need to edit this string to replace myOtherServlet
with the URI I want.
Non Tymeleaf Attempt 1
@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();
}
}
page.html:
th:text="${@urlUtils.getAbsoluteUrlTo('/myServlet', 'myParam', ${dynamicParameter})}"
The problem is the host name that can be aliased before it reaches my server (see this). Thymeleaf+JS Sollution
Using some java script plus thymeleaf
<p id="myUrl" th:text="@{/myServlet(myParam=${dynamicParameter})}" />
<script type="text/javascript">
$(document).ready(function () {
var myUrl= $("#myUrl");
myUrl.text(window.location.origin + myUrl.text());
});
</script>