SpringBoot遇到的问题--无法请求html等静态资源文件.md

Posted by lizhao on 07-09,2019

SpringBoot遇到的问题--无法请求html等静态资源文件,webapp或者resources/static

问题

我遇到的问题是,无法访问静态资源文件,html。

文件时放到webapp目录下面

也有部分文件放在resources

解决方案

未设置打包时添加至jar包

这个只要在pom.xml中的bulid节点添加:

<!-- 添加这个就可以是webapp目录生效 -->
<resources>
    <resource>
        <directory>src/main/webapp</directory>
        <!--注意此次必须要放在此目录下才能被访问到 -->
        <targetPath>META-INF/resources</targetPath>
        <includes>
            <include>**/**</include>
        </includes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
            <include>**/*</include>
        </includes>
    </resource>
</resources>

设置了自定义拦截器,导致静态资源无法获取

这个问题搞掉了我一天半的时间, 设置了拦截器,我们的静态资源目录需要重写在方法里面:

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/") .addResourceLocations("classpath:/resources/").addResourceLocations("classpath:/static/")
            .addResourceLocations("classpath:/public/");
    super.addResourceHandlers(registry);
}
@SpringBootApplication
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {

        String[] excludes = new String[] { "/static/**", "**.html", "/login.html" };

        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/resources/").addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        super.addResourceHandlers(registry);
    }
}