Spring MVC:如何在Thymeleaf中获取当前URL

34
我正在使用Thymeleaf模板引擎与Spring Web MVC,并且在创建带有当前URL的URL时遇到了困难。是否有办法在Thymeleaf HTML文件中获取当前URL?例如:假设我的浏览器地址栏中的当前URL为:http://localhost:8080/project/web/category/mobiles,现在我想要创建一个URL,如http://localhost:8080/project/web/category/mobiles/store/samsunghttp://localhost:8080/project/web/category/mobiles?min_price=10&max_price=100。因此,代码将如下所示:
<a th:with="currentUrl='http://localhost:8080/project/web/category/mobiles'" 
   th:href="@{__${currentUrl}__/__${store.name}__}">
    Click to More Result
</a>

这里我使用了一个名为currentUrl的变量,其中包含硬编码的URL,因此我希望找到一些解决方案。硬编码的值并不总是适用,因为我有动态类别。 我尝试使用相对URL,但对我来说没有起作用。
<a th:href="@{/store/__${store.name}__}">Click to More</a>

//will produce: http://localhost:8080/project/web/store/samsung
//I want: http://localhost:8080/project/web/category/mobiles/store/samsung

请看一下,如果我做错了什么,请告诉我。

2
为什么需要完整的URL?为什么不直接使用相对URL? - M. Deinum
在我的情况下,http://localhost:8080/project 是我的基本 URL,/web/category/{categoryName} 由控制器映射。我尝试了相对路径,但似乎不起作用,我正在使用 <a th:href="@{/store/__${store.name}__}>" 点击查看更多</a> 来生成相对 URL。 - Anil Kumar Pandey
4个回答

46

哦,我找到了解决方案。我在文档中漏掉了{#httpServletRequest.requestURI}

这里是对我有效的解决方案:

<a th:href="@{__${#httpServletRequest.requestURI}__/store/__${store.name}__}">Click to More</a>
//Will produce: http://localhost:8080/project/web/category/mobiles/store/samsung

1
${#httpServletRequest.requestURI} 运行良好(Thymeleaf Spring4 2.1.5) - klakegg
3
在我的应用程序中,requestURI 给我类似于这样的内容:[/store/something],而 requestURL 给我类似于这样的内容:[https://www.example.com/store/something]。基于我的使用情况,我选择了 requestURL,因为完整的 URL 更适合我使用。 - Ng Sek Long
5
给未来的读者:在Thymeleaf 3.0中,您可以使用${#request.requestURI}(链接)[https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-basic-objects]。 - user2652379
4
请注意,#httpServletRequest.requestURI 不包括查询字符串或片段。 - cdalxndr

30

您可以使用两个单引号'来获取当前URL。示例:

<a th:href="@{''(lang=de)}">Deutsch</a>

请注意,遗憾的是,这不包括现有的URL参数。


我刚刚再次尝试了一下,它有效...: <a th:href="@{''}">当前页面</a>。你的 Thymeleaf 版本是多少?我使用的是 3.0.2 版本。 - yglodt
我也没成功。我使用的是3.0.3版本;你的示例呈现为<a href="">Current Page</a> - end-user
2
不错的解决方案。这里使用的是Spring 5.0.4,Spring Boot 2.0和Thymeleaf 3.0.9。 - Michael
2
请注意,尽管这个方法可行,但它不会返回完整的URL;它只生成相对URL。 - Peter Chaula

9
在Thymeleaf 3.1中,可以从上下文对象中获取当前URL:
<form th:action="${#ctx.springRequestContext.requestUri}">

仍然适用于Spring-Boot 3.1.1。 - Valerij Dobler
不再适用于Spring Boot 3.1.5版本。 我不明白为什么移除了这个功能。能否解释一下这个变化将会很好。我相信Thymeleaf团队有充分的理由这样做。 - undefined
这是解释的链接:https://github.com/thymeleaf/thymeleaf/issues/886 - undefined

3
如果请求的url是这样的: http://localhost:8080/my-page 我可以使用 httpServletRequest.requestURI 来获取这个值:/my-page 例如,如果你需要加载一些资源,你可以使用:
<script th:src="@{|${#httpServletRequest.requestURI}/main.js|}"></script>

渲染后的HTML将是:

<script src="/my-page/main.js"></script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接