java - 如何在 thymeleaf 中构建绝对 URL?

标签 java spring-mvc thymeleaf

我想显示运行时生成的带参数的绝对 URL。不创建页面的 href,而是使用 th:text 显示 URL 。有什么简单的方法可以使用 Tymeleaf 执行此操作(无需连接 #request 对象中的 URL 片段,也无需使用某些 MVC 实用程序类)?

尝试 1

<p th:text="@{/myServlet(myParam=${dynamicParameter})}" /> - 仅显示 URL 的一部分,省略协议(protocol)、端口和主机名。我得到/myServlet?myParam=123 。与 th:href 的行为相同,如果您检查 <a>您将看到相同的 href - 在这种情况下,浏览器会通过推断协议(protocol)、端口等提供帮助

尝试 2

th:text="@{__${#httpServletRequest.requestURI}__}" - 生成当前页面的相对 URI,不包括协议(protocol)等

尝试3

th:text="@{__${#httpServletRequest.requestURL}__}" - 这次生成当前页面的绝对 URL,其中包含协议(protocol)、主机和 servlet 上下文。现在的问题是,当我从不同的页面显示此文本时,我的 URL 是 ...myApp/myOtherServlet所以我需要编辑这个字符串来替换 myOtherServlet与我想要的 URI。

非 Tymeleaf 尝试 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();
    }
}

页面.html:

th:text="${@urlUtils.getAbsoluteUrlTo('/myServlet', 'myParam', ${dynamicParameter})}"

问题在于主机名在到达我的服务器之前可以使用别名(请参阅 this )。 Thymeleaf+JS解决方案

使用一些java脚本加上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>

最佳答案

您可以即时连接 servlet 请求:

th:text="${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+@{/myServlet(myParam=${dynamicParameter})}"

或者对于 JavaScript:

<script type="text/javascript">
    GLOBAL.serverURI = '[[${#httpServletRequest.scheme}+'://'+${#httpServletRequest.serverName}+':'+${#httpServletRequest.serverPort}+@{/myServlet(myParam=${dynamicParameter})}]]';
</script>

关于java - 如何在 thymeleaf 中构建绝对 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751265/

相关文章:

java - Spring MVC 和 JUnit : Failed to load ApplicationContext

java - 如何保持 2 个 JPanel 彼此垂直对齐?

java - Spring禁用上下文:component-scan does not detect controllers

java - 创建名称为 'serviceController' : Injection of autowired dependencies failed; 的 bean 时出错

jar - Spring Boot Thymeleaf 片段子目录 View 错误与 jar

java - 如何使用thymeleaf在页面源代码中打印mensagens?

java - Thymeleaf Rich HTML 电子邮件错误

java - 在 Derby 和 Hsqldb 中转义表名和字段名的问题

java - 获取maven项目的所有依赖

java - 如何使用@ContextConfiguration配置另一个项目的值