Java项目中HTML页面引用resources下图片无法显示如何解决
Java项目resources目录下图片无法在HTML加载的解决方案
问题根因
你当前使用的是典型的Spring Boot Maven项目结构,src/main/resources对应类路径(classpath)根目录,Spring Boot默认只会扫描以下4个路径下的静态资源:
classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/
你把图片存放在classpath:/images/下,不在默认扫描范围内,所以无法被访问到。同时使用./开头的相对路径容易受HTML文件本身的访问层级影响,也会导致路径匹配失败。
可行解决方案
方案1:调整资源存放路径(最推荐,无需修改配置)
直接在src/main/resources目录下新建static文件夹,将整个images文件夹移动到static目录内,最终图片路径为:src/main/resources/static/images/piechart.jpg
修改HTML的img标签src属性为根路径写法:
<img style="max-width: 170px;" src="/images/piechart.jpg" alt="pie-chart">
方案2:手动配置静态资源映射(不想改目录时使用)
如果需要保留现有src/main/resources/images的目录结构,手动添加静态资源映射规则即可:
方式A:修改配置文件
在application.properties中添加如下配置:
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/
方式B:编写Java配置类
新增Web配置类实现自定义资源映射:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/images/**") .addResourceLocations("classpath:/images/"); } }
配置完成后同样使用src="/images/piechart.jpg"即可访问图片。
其他常见排查点
- 检查编译后的
target/classes目录下是否存在对应图片文件,若不存在可以手动执行mvn compile命令触发资源编译,或者重启IDE - 如果项目配置了上下文路径,比如
application.properties中存在server.servlet.context-path=/security配置,需要将src修改为/security/images/piechart.jpg;如果使用Thymeleaf模板引擎,推荐使用th:src="@{/images/piechart.jpg}"自动拼接上下文路径 - 你的项目名包含security字样,大概率集成了Spring Security安全框架,需要在安全配置中放行静态资源:
// Spring Security 6.x 配置示例 @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/images/**").permitAll() .anyRequest().authenticated() ); return http.build(); }
内容的提问来源于stack exchange,提问作者Jsef bch
相关产品推荐
相关产品推荐

