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

Spring Boot整合Thymeleaf时HTML页面图片无法显示求助

Spring Boot + Thymeleaf 图片无法显示的解决方案

问题根源

你当前写的图片路径/src/main/resources/static/image.png是本地开发的物理路径,项目打包运行后根本不存在这个路径;同时你的目录结构里没有Spring Boot默认识别的static静态资源目录,图片直接放在src/main/resources/images下,不符合框架的静态资源加载规则,所以图片无法显示。

解决步骤

1. 调整目录结构(推荐方案)

Spring Boot默认会把src/main/resources/static作为静态资源根目录,将images文件夹移到static下,调整后的目录结构如下:

🗁 src
 └─── 🗁 main
         └─── 🗁 resources
                   ├─── 🗁 templates
                   └─── 🗁 static
                           ├─── 🗁 css
                           └─── 🗁 images

2. 使用Thymeleaf标准URL表达式引用图片

在HTML中用Thymeleaf的@{}语法引用图片,它会自动处理项目上下文路径,避免路径错误:

<img th:src="@{/images/image.png}" alt="images">

注:这里的/images对应static/images的路径,Thymeleaf会自动映射到静态资源目录。

备选方案:不移动目录,配置静态资源路径

如果不想调整目录,可在application.properties(或application.yml)中添加配置,让Spring Boot识别resources/images作为静态资源目录:

spring.web.resources.static-locations=classpath:/templates/,classpath:/css/,classpath:/images/

之后同样用Thymeleaf的URL表达式引用:

<img th:src="@{/image.png}" alt="images">

(若图片在images的子目录中,补充对应子路径即可)

额外注意事项

  • 确保HTML文件已正确引入Thymeleaf命名空间:在<html>标签中添加xmlns:th="http://www.thymeleaf.org"
  • 检查图片文件名和路径的大小写一致性,Linux环境下大小写敏感,避免打包到服务器后出现问题
  • 清理浏览器缓存,旧缓存可能导致图片无法正常加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:18:19