我有一个带有获取参数的现有 URL。单击按钮时,我想更改一个特定的 URL 参数,但保留其他参数。这可能吗?
Thymeleaf 模板:
<a th:href="@{/order/details(id=3)}">
结果:
<a href="/order/details?id=3">
如果我想怎么办
- 保留 URL 中的其他参数
- 覆盖
id
参数?
上述 thymeleaf 模板的预期结果:
localhost:8080/order/details?name=test&id=3
最好不要使用 javascript。
最佳答案
尽管这是一个较老的问题,但我希望这仍然能有所帮助:
<a th:href="@{${urlBuilder.replaceQueryParam('id', 3).build().toUriString()}}" th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder).fromCurrentRequest()}">
这构建了一个完整的 URI 字符串,包括 HTTP(S) 部分。因此,如果您(例如)为您的 Web 应用程序使用负载平衡器并且它不直接转发 https 请求,您将得到错误的 URI 字符串。在这种情况下,您必须像 Zico 那样做写道:在 Controller 中设置 baseUrl 并将其绑定(bind)到模板。
您还可以从当前请求中获取查询字符串:request.getQueryString()
或在您的 Controller 中使用 ServletUriComponentsBuilder
类。
编辑
您可以将 .scheme('https')
应用于 urlBuilder
(@{${urlBuilder.replaceQueryParam('id', 3).scheme( 'https').build().toUriString()}}
).例如。您可以在 Controller 中创建一个方法,从您的负载均衡器获取 X-Forwarded-Proto
。
关于java - 如何替换 thymeleaf 链接中的 URL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45594238/