【问题标题】:I need to create absolute URL's for my SPRING application using Thymeleaf我需要使用 Thymeleaf 为我的 SPRING 应用程序创建绝对 URL
【发布时间】:2014-03-29 03:36:30
【问题描述】:

我有一个直接在 Java 或 Tomcat 7 服务器上运行(使用 spring boot)的 SPRING 应用程序。我需要为几个页面(映射)创建绝对 URL,以便可以通过电子邮件发送这些链接。

我以为这很简单,但现在似乎很难。我更喜欢 100% 用 Thymeleaf 编写的解决方案,但如果这不可能,我当然可以从我的 Java 代码中为 Thymeleaf 提供一些变量。

以前有人在 Thymeleaf 中解决过这个问题吗?

【问题讨论】:

    标签: java spring spring-mvc thymeleaf


    【解决方案1】:

    今天我做了一个集成,建议使用完整的 Url 以实现兼容性。

    • 基础应该根据环境变化(我只是将它作为属性发送)。

    • 最后一个@{/js/i/dyn}是获取contextPath。

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

    参考:http://www.thymeleaf.org/doc/articles/standardurlsyntax.html

    【讨论】:

      【解决方案2】:

      我只是在使用 Thymeleaf 生成 HTML 电子邮件时做了类似的事情(因此当然必须将链接设为绝对链接)。我使用 Thymeleaf 的内置 @{} 链接语法来创建相对于服务器的适当 URL(因为它调用了我需要做的 HttpServletResponse.encodeURL(),因为我有一个自定义实现来做一些额外的 URL 修改),然后使用Spring 的 ServletUriComponentsBuilder 使用 HttpServletRequest 服务器信息使 URL 成为绝对 URL。

      <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>
      

      可能有更好的方法,但这对我来说效果很好,并且完全在 Thymeleaf 中制作绝对 URL(尽管使用 Spring 的库)。

      【讨论】:

        【解决方案3】:

        在我看来,您应该在属性文件中提供服务器 URL,然后在 Thymeleaf 中访问它。您可以通过在视图中访问 Spring Bean 来做到这一点:

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

        在上面的例子中,urlService 是一个 Spring Bean。

        请看这个答案:https://stackoverflow.com/a/675903/718515

        您可能还对可让您访问servletContext 的#ctx 变量感兴趣。请参阅 Thymeleaf 文档:http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html#base-objects

        希望对你有帮助!

        【讨论】:

        • Thymeleaf 文档的链接现已失效。
        猜你喜欢
        • 2021-10-16
        • 1970-01-01
        • 2013-02-15
        • 1970-01-01
        • 2012-02-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-24
        相关资源
        最近更新 更多