springboot 访问不到静态资源问题汇总

时间:2025-03-21 10:22:03

方法一:

添加java配置类,手动配置:

package com.demo.demo.Controller;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 
 
@Configuration
public class UsingStaticController extends WebMvcConfigurationSupport {
 
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
// classpath表示在resource目录下,/static/** 表示在URL路径中访问如 
// http://localhost:8080/static/ 即可访问到resource下的static目录
      registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

失败了

方法二:

yml文件手动配置静态资源配置路径:

#thymeleaf
  thymeleaf:
    cache: false
    prefix:  classpath:/templates/
    check-template-location: true
    suffix: .html
    encoding: utf-8
    mode: HTML
#这个是关键,放开springboot对静态资源的拦截
  mvc:
    static-path-pattern: /static/**

还是失败了

方法三:

将extends WebMvcConfigurationSupport改为implements WebMvcConfigurer 。并且在中填入


```yaml
-path-pattern: /static/**

还是失败了

方法四

检查pom配置
发现配置了这个

<resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

删除后,成功