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

Spring MVC+Thymeleaf中基于用户声望显示图片的语法问题

解决Thymeleaf Switch-Case范围判断的XML解析错误与用法问题

你遇到的问题其实分两部分:一是XML解析时的实体引用错误,二是Thymeleaf th:switch的用法不太适合范围判断场景,咱们一步步来解决:

1. 直接解决XML解析错误

报错The entity name must immediately follow the '&' in the entity reference是因为你错误地重复转义了比较运算符:

  • 你写了<,这会被XML解析器先把&转成&,剩下的lt;就变成了<——这相当于在模板里写了& lt;,而XML要求&后面必须紧跟合法的实体名称,所以触发了错误。
  • 正确的转义规则应该是:
    • < → &lt;
    • > → &gt;
    • && → &amp;&amp;

2. 调整Switch-Case的写法(适配范围判断)

Thymeleaf的th:switch原本是为精确值匹配设计的,但我们可以通过把switch的目标设为true,让每个th:case对应一个布尔表达式,来实现范围判断:

<th:block th:switch="true">
    <div th:case="${reputation &lt; 0}">
        <img th:src="@{/css/img/troll.png}"/>
    </div>
    <div th:case="${reputation == 0}">
        <img th:src="@{/css/img/smeagol.jpg}"/>
    </div>
    <div th:case="${reputation &gt; 0 &amp;&amp; reputation &lt; 5}">
        <img th:src="@{/css/img/samwise.png}"/>
    </div>
    <div th:case="${reputation &gt;= 5 &amp;&amp; reputation &lt;= 15}">
        <img th:src="@{/css/img/frodo.png}"/>
    </div>
    <div th:case="${reputation &gt; 15}">
        <img th:src="@{/css/img/gandalf.jpg}"/>
    </div>
</th:block>

3. 更推荐的方案:用th:if或三元表达式

其实对于范围判断来说,th:if的写法更直观,可读性更强,完全不需要依赖switch-case:

<div th:if="${reputation &lt; 0}">
    <img th:src="@{/css/img/troll.png}"/>
</div>
<div th:if="${reputation == 0}">
    <img th:src="@{/css/img/smeagol.jpg}"/>
</div>
<div th:if="${reputation &gt; 0 &amp;&amp; reputation &lt; 5}">
    <img th:src="@{/css/img/samwise.png}"/>
</div>
<div th:if="${reputation &gt;= 5 &amp;&amp; reputation &lt;= 15}">
    <img th:src="@{/css/img/frodo.png}"/>
</div>
<div th:if="${reputation &gt; 15}">
    <img th:src="@{/css/img/gandalf.jpg}"/>
</div>

如果想让代码更紧凑,还可以用三元表达式直接赋值给th:src:

<img th:src="@{${reputation < 0 ? '/css/img/troll.png' : 
                          reputation == 0 ? '/css/img/smeagol.jpg' : 
                          reputation < 5 ? '/css/img/samwise.png' : 
                          reputation <= 15 ? '/css/img/frodo.png' : '/css/img/gandalf.jpg'}}"/>

这样一行代码就搞定了所有判断逻辑,也避免了多个div嵌套。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:35:35