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

Spring Boot项目Spring MVC控制器无法加载静态图片问题及解决

更新说明

按照M. Deinum的建议使用ClassPathResource后问题已成功解决,我同时移除了WebMvcConfig配置类,暂不确定该操作是否与问题修复相关。

@RequestMapping(value = "/image", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getImage() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("static/images/user-default.png");
        InputStream in = classPathResource.getInputStream();
        return IOUtils.toByteArray(in);
    }

问题描述

我正在开发采用Spring MVC架构、集成Spring Security的Spring Boot项目,遇到了控制器无法找到指定图片的问题,暂无法定位MVC配置的错误点。
我的图片服务控制器代码如下:

@Controller
public class ImageController {
    @Autowired
    private ServletContext servletContext;
    
    @RequestMapping(value = "/image", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getImage() throws IOException {
        InputStream in = servletContext.getResourceAsStream("/images/user-default.png");
        return IOUtils.toByteArray(in);
    }
}

调试后发现方法中获取的InputStream为null,但通过两种方式可正常加载图片:一是在Thymeleaf模板中引用资源,二是直接访问资源路径,两种方式均可在浏览器中正常查看图片。

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<!--省略非核心代码-->
<img th:src="@{/images/quiz-academic.png}"/> <!--该写法生效,图片可在浏览器正常显示-->
<!--省略非核心代码-->
</html>

直接访问路径测试效果:

http://localhost:8080/images/user-default.png (该路径生效,图片可在浏览器正常显示)

我不清楚为什么控制器无法读取图片,但Thymeleaf引用、直接访问路径两种方式均可正常加载资源,以下是我的相关配置:

MVC配置代码

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/", "classpath:/static/", "classpath:/images/");
    }
}

Security配置代码

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/error");
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .antMatchers("/admin/**").access("hasAnyRole('ROLE_ADMIN')")
                .antMatchers("/user").access("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
                .antMatchers("/css/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/image").permitAll()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated();
                /* 登录/登出配置省略 */
    }
}

项目目录结构

src/main/java/com/kjnts/springwebapp/config/WebSecurityConfig.java
src/main/java/com/kjnts/springwebapp/config/WebMvcConfig.java
src/main/java/com/kjnts/springwebapp/controller/ImageController.java
src/main/resources/static/images/user-default.png
src/main/resources/templates/user-profile.html

补充说明:我未使用XML格式的Spring配置,恳请协助排查问题原因,谢谢。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:06:06