我正在将 Thymeleaf 模板引擎与 Spring Web MVC 一起使用,并且在当前 url 的帮助下创建 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>
这里我使用
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
请看一下,如果我做错了什么,请告诉我。
哦,我找到了解决方案。我错过了文档中的
{#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
您可以使用两个单引号
'
获取当前 URL。示例:
<a th:href="@{''(lang=de)}">Deutsch</a>
请注意,遗憾的是,这不包括现有的 URL 参数。
在 Thymeleaf 3.1 中,可以从 context 对象中获取当前 URL:
<form th:action="${#ctx.springRequestContext.requestUri}">
如果请求的网址例如: 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>
从 Thymeleaf 3.1 开始,默认情况下似乎无法访问当前请求。
您需要手动将其添加到上下文中,例如:
@ModelAttribute
public String currentUrl(HttpServletRequest request) {
return request.getRequestURI();
}
<a th:href="@{__${currentUrl}__/__${store.name}__}">
Click to More Result
</a>