You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SpringBoot中用ThymeLeaf生成含#的href链接?

解决Thymeleaf生成SPA深度链接(保留#)的问题

问题说明

需要生成符合以下格式的SPA深度链接,其中12345为可变产品ID,URL中的#必须保留(单页应用路由要求):

<a href="http://myhost/myapp/#/products/12345/details">...</a>

尝试两种模板写法均未达到预期:

  • 直接在th:href中包含#和参数占位符:

    <a th:href="@{http://myhost/myapp/#/products/{productId}/details(productId=${product.id})}">...</a>
    

    生成结果错误:参数被转为查询字符串,#后的占位符未替换

    .../myapp?productId=12345#/products/{productId}/details
    
  • 用th:with拼接带#的路径:

    <a th:with="productLink=${'#/products/' + product.id + '/details'}"
       th:href="@{http://myhost/myapp/{productLink}(productLink=${productLink})}">...</a>
    

    生成结果中#被编码为%23,不符合要求:

    <a href="http://myhost/myapp/%23/products/12345/details">...</a>
    

可行解决方案

方法1:直接拼接完整URL字符串

跳过Thymeleaf的URL表达式(@{...}),直接拼接完整URL,避免编码和参数解析干扰:

<a th:href="${'http://myhost/myapp/#/products/' + product.id + '/details'}">...</a>

此方法直接生成符合要求的链接,#保持原样,产品ID正确替换。

方法2:拆分基础路径与哈希片段拼接

如果需要通过Thymeleaf管理基础路径(比如从配置动态获取),可以拆分基础路径和哈希部分分别处理:

<a th:href="@{http://myhost/myapp/} + '#/products/' + ${product.id} + '/details'">...</a>

@{http://myhost/myapp/}负责生成规范的基础路径,后续直接拼接未编码的哈希片段,确保#保留在正确位置。

方法3:结合Thymeleaf工具类规范处理路径(可选)

若需对路径中的特殊字符编码,可使用Thymeleaf的#uris工具类,手动保留#:

<a th:href="@{http://myhost/myapp/} + '#' + ${#uris.escapePath('/products/' + product.id + '/details')}">...</a>

该方式会对路径内的特殊字符进行编码,同时保证#不被转义。

内容的提问来源于stack exchange,提问作者fml2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:20:02