I just did something similar where I was using Thymeleaf to generate an HTML email (and so of course links had to be made absolute). I used Thymeleaf's built-in @{}
link syntax to create the appropriate URL relative to the server (since it calls the HttpServletResponse.encodeURL()
which I needed to do as I had a custom implementation to do some additional URL munging), and then uses Spring's ServletUriComponentsBuilder to make the URL absolute using the HttpServletRequest server information.
<p th:with="
relativeCustomerInfoPath=@{|/my/path/${customer.code}/info/|},
customerInfoPath=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder).fromContextPath(#httpServletRequest).replacePath(relativeCouponPath).toUriString()}">
Go see your info at
<<a th:href="${customerInfoPath}" th:text="${customerInfoPath}">Link</a>>.
</p>
There may be a better way, but this worked well for me and does the making of the URL absolute entirely within Thymeleaf (though using Spring's library).