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

如何使用Thymeleaf通过URL显示图片?

解决方案

不需要用JavaScript,直接用Thymeleaf的属性绑定就能搞定,步骤如下:

  1. 替换显示URL的单元格
    把原来的<td th:text="${person.image}" />替换成<img>标签,用th:src动态绑定Person对象里的image字段值,同时可以加上alt属性提升可访问性:
<td>
    <img th:src="${person.image}" th:alt="${person.name}" style="width: 100px; height: auto;" />
</td>
  1. 修改后的完整表格代码
    替换后的表格tbody部分应该是这样:
<tbody>
    <!-- Looping over data -->
    <tr th:each="person: ${person}">
    
        <td th:text="${person.name}" />
        <td>
            <img th:src="${person.image}" th:alt="${person.name}" style="width: 100px; height: auto;" />
        </td>
        <td th:text="${person.number}" />

        <td>
        </td>
    </tr>   
</tbody>
  1. 注意事项
  • 如果你的image字段存的是绝对URL(比如https://example.com/avatar.jpg),直接用上面的代码就能正常显示。
  • 如果是相对URL(比如/images/avatar.jpg),要确保图片放在Spring Boot项目的src/main/resources/static/images/目录下,Spring会自动映射静态资源,这样访问路径才有效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:40:50