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

SpringBoot应用(上下文platsBruts)Thymeleaf href非硬编码配置问题

解决Spring Boot + Thymeleaf不硬编码应用上下文设置href的问题

嘿,我来帮你搞定这个Thymeleaf href的问题!你的Spring Boot应用上下文是platsBruts,想要不硬编码上下文的话,其实Thymeleaf的标准表达式就已经帮你处理好啦,之前的写法都有小问题,我给你纠正下:

正确的写法

直接使用Thymeleaf的@{...}URL表达式就行,它会自动拼接上你的应用上下文路径:

<a th:href="@{/pistoles/list/}" class="pure-menu-link">你的链接文本</a>

渲染之后,最终的href会自动变成/platsBruts/pistoles/list/,完全不用你手动写上下文路径,完美解决硬编码的问题。

你之前写法的错误原因

  • 第一种写法<a th:href="/*[[@{/pistoles/list/}]]*/" class="pure-menu-link">:
    这里的语法完全错误,/* */是HTML注释,里面的Thymeleaf表达式不会被解析;而且[[...]]是Thymeleaf的内联文本表达式,不该用在th:href属性里,所以Thymeleaf才会报错“Could not parse as expression”。

  • 第二种写法<a href="/pistoles/list/}" class="pure-menu-link">:
    首先这里多了一个多余的闭合大括号},就算去掉这个错误,原生的href属性不会自动拼接应用上下文,最终路径会是/pistoles/list/,而不是带platsBruts的正确路径,自然无法访问到对应接口。

额外小技巧(如果需要在JS里用上下文路径)

如果你的JavaScript代码里也需要用到应用上下文,可以用Thymeleaf的内联表达式先把上下文路径存起来:

<script th:inline="javascript">
    const contextPath = [[@{/}]];
    // 之后就可以用它拼接路径:比如 contextPath + 'pistoles/list/'
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:39:21