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

Ani*_*dey 18 spring-mvc thymeleaf

我正在使用Thymeleaf模板引擎和Spring Web MVC,我在当前网址的帮助下创建url时遇到困难.有没有办法在Thymeleaf HTML文件中获取最新信息?例如:假设我的浏览器地址栏中的当前网址为:

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>
Run Code Online (Sandbox Code Playgroud)

这里我使用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
Run Code Online (Sandbox Code Playgroud)

请看看,如果我做错了,请告诉我.

Ani*_*dey 33

哦,我得到了解决方案.我错过{#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
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“#httpServletRequest.requestURI”不包含查询字符串或片段。 (4认同)
  • 对于未来的读者;[你可以在 Thymeleaf 3.0(Link) 中使用 `${#request.requestURI}`](https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-basic-objects) (3认同)
  • 在我的应用程序中,requestURI给我这样的东西:[/ store / something],而requestURL给我这样的东西:[https://www.example.com/store/something]。我选择requestURL,因为完整的URL对于我的用例来说更好。 (2认同)

ygl*_*odt 20

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

<a th:href="@{''(lang=de)}">Deutsch</a>
Run Code Online (Sandbox Code Playgroud)

请注意,这不幸地不包括现有的URL参数.

  • 不错的解决方案。适用于 Spring 5.0.4、Spring Boot 2.0、Thymeleaf 3.0.9 (2认同)
  • 请注意,虽然这有效,但它不会返回完整的 url;它生成相对网址 (2认同)

Vác*_*žel 10

在 Thymeleaf 3.1 中,可以从 context 对象获取当前 URL:

<form th:action="${#ctx.springRequestContext.requestUri}">
Run Code Online (Sandbox Code Playgroud)

  • 这是解释:https://github.com/thymeleaf/thymeleaf/issues/886 (2认同)