3

I have a SPRING application running (using spring boot) either directly on Java or on a Tomcat 7 server. I need to create absolute URL's for a couple of pages (mappings) so that these links can be sent via e-mail.

I thought this would be simple, but now it seems hard. I would prefer a solution that is 100% written in Thymeleaf, but if that is not possible, I can certainly provide Thymeleaf with some variables from my Java code.

Anyone solved this before in Thymeleaf?

3 Answers 3

3

In my opinion, you should provide a server URL in a property file and than access it in Thymeleaf. You can do it by accessing Spring Bean in a view:

<div th:text="${@urlService.getApplicationUrl()}">...</div> 

In the above example, the urlService is a Spring Bean.

Please see this answer: https://stackoverflow.com/a/675903/718515

You may be also interested in #ctx variable that gives you access to servletContext. See Thymeleaf docuementation: http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html#base-objects

I hope it helps!

Sign up to request clarification or add additional context in comments.

1 Comment

The link to Thymeleaf documentation is now dead.
1

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 
  &lt;<a th:href="${customerInfoPath}" th:text="${customerInfoPath}">Link</a>&gt;.
</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).

Comments

0

Today I made an integration that suggested using the full Url for compatibility.

  • The base should change according to enviroment (I just send it as attribute).

  • The last @{/js/i/dyn} is to get the contextPath.

<script th:src="${'https://' + base} + @{/js/i/dyn}"></script>

ref: http://www.thymeleaf.org/doc/articles/standardurlsyntax.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.