扩展WebMvcConfigurer后无法从静态目录中获取任何文件 [英] Can't get any files from static directory after extending WebMvcConfigurer

查看:77
本文介绍了扩展WebMvcConfigurer后无法从静态目录中获取任何文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构

我使用的依赖项:

  • spring-boot-starter
  • spring-boot-starter-test
  • spring-boot-starter-web
  • spring-boot-starter-thymeleaf
  • spring-boot-starter-security
  • thymeleaf-extras-springsecurity5
  • mysql-connector-java
  • spring-boot-starter-data-jpa
@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/icon/**").addResourceLocations("classpath:/static/img/icon/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }

}

我在 index.html 中尝试过这些

I have tried these in index.html

<img src="icon/signin.svg">
<img src="/icon/signin.svg">
<img src="./icon/signin.svg">
<img src="../static/img/icon/signin.svg">

失败.此外,我试图将资源目录移动到主目录,什么也没有.有什么想法吗?

unsuccesfully. In addition i tried to move resources directory to main directory, nothing. Any idea?

推荐答案

当您添加 @EnableWebMvc 时,您会覆盖 SpringBoot 的所有自动配置.这应该有效:

When you add @EnableWebMvc you override all auto configuration by SpringBoot. This should work:

@Configuration
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/icon/**").addResourceLocations("classpath:/static/img/icon/");
    }
}

此外,我刚刚查看了您的目录结构图片,除非我睁开眼睛,否则我可以肯定您的资源"已被删除.文件夹不在 src/main 下.它应该在 java 文件夹旁边:

Also I just had a look at the picture of your directory structure and I am certain unless my eyes are off is that your "resources" folder is not under src/main. It should be right beside the java folder:

src
|_ main
      |_ java
      |_ resources

这篇关于扩展WebMvcConfigurer后无法从静态目录中获取任何文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆