【问题标题】:Spring MVC: How do I get current url in ThymeleafSpring MVC:如何在 Thymeleaf 中获取当前 url
【发布时间】:2014-06-21 09:07:51
【问题描述】:

我正在将Thymeleaf Template Engine 与 Spring Web MVC 一起使用,但在当前 url 的帮助下创建 url 时我被卡住了。有没有办法在 Thymeleaf HTML 文件中获取最新信息? eg:假设我当前浏览器地址栏中的url是:

http://localhost:8080/project/web/category/mobiles

现在我想创建一个这样的网址http://localhost:8080/project/web/category/mobiles/store/samsung

http://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>

这里我使用带有硬编码 url 的 currentUrl 变量,所以我想要一些相同的解决方案。硬编码值不会每次都有效,因为我有动态类别。

我对相对 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

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

【问题讨论】:

  • 为什么需要完整的 URL?为什么不简单地使用相对 URL?
  • 在我的情况下,http://localhost:8080/project 是我的基本网址,/web/category/{categoryName} 由控制器映射。我尝试了相对但它似乎不起作用,我将它用于相对网址&lt;a th:href="@{/store/__${store.name}__}&gt;" Click to More&lt;/a&gt;

标签: spring-mvc thymeleaf


【解决方案1】:

哦,我找到了解决方案。我错过了文档中的{#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

【讨论】:

  • ${#httpServletRequest.requestURI} 工作得很好(Thymeleaf Spring4 2.1.5)
  • 在我的应用程序中,requestURI 给我这样的东西:[/store/something] 而 requestURL 给我这样的东西:[example.com/store/something]。我选择 requestURL 因为完整的 url 更适合我的用例。
  • 请注意#httpServletRequest.requestURI 不包括查询字符串或片段。
【解决方案2】:

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

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

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

【讨论】:

  • 我刚刚又试了一次,它成功了...:当前页面。你的 Thymeleaf 版本是什么?我用的是 3.0.2。
  • 对我也不起作用。我正在使用 3.0.3;你的例子呈现了这个&lt;a href=""&gt;Current Page&lt;/a&gt;
  • 不错的解决方案。适用于 Spring 5.0.4、Spring Boot 2.0、Thymeleaf 3.0.9
  • 请注意,虽然这可行,但它不会返回完整的 url;它生成相对网址
【解决方案3】:

如果请求的 url 例如:http://localhost:8080/my-page

我可以得到这个值:/my-page 使用这个:httpServletRequest.requestURI

例如,如果你必须加载一些资源,你可以使用:

<script th:src="@{|${#httpServletRequest.requestURI}/main.js|}"></script>

渲染后的 html 将是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2023-03-16
    • 2010-12-02
    相关资源
    最近更新 更多