我无法让Spring-boot项目提供静态内容。
我在src/main/resources下放置了一个名为static的文件夹。其中有一个名为images的文件夹。当我将应用程序打包并运行时,它无法找到我放在该文件夹中的图像。
我试着把静态文件放在公共、资源和META-INF/资源中,但都不起作用。
如果我jar -tvf app.jar,我可以看到文件在jar的右边文件夹:
/static/images/head.png为例,但调用:http://localhost:8080/images/head.png,我得到的是一个404
知道为什么弹簧靴找不到这个吗?(我使用1.1.4 BTW)
只是为一个老问题补充另一个答案……人们已经提到@EnableWebMvc将阻止WebMvcAutoConfiguration加载,这是负责创建静态资源处理程序的代码。还有其他一些条件也会阻止WebMvcAutoConfiguration的加载。要明白这一点,最明确的方法是查看源代码:
https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java#L139-L141
在我的例子中,我包括了一个库,它有一个从WebMvcConfigurationSupport扩展的类,这是一个将阻止自动配置的条件:
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
重要的是不要从WebMvcConfigurationSupport扩展。相反,从WebMvcConfigurerAdapter扩展。
更新:正确的方法做到这一点在5。实现WebMvcConfigurer
在我的例子中,一些静态文件没有提供,比如.woff字体和一些图像。但是css和js工作得很好。
更新:让Spring Boot正确地服务于woff字体的一个更好的解决方案是配置这个答案中提到的资源过滤,例如(注意,你需要包括和排除):
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>static/aui/fonts/**</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>static/aui/fonts/**</include>
</includes>
</resource>
</resources>
-----旧的解决方案(工作,但会破坏一些字体)-----
另一个解决方案是使用setUseSuffixPatternMatch(false)禁用后缀模式匹配
@Configuration
public class StaticResourceConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// disable suffix matching to serve .woff, images, etc.
configurer.setUseSuffixPatternMatch(false);
}
}
致谢:@Abhiji确实给了我4分。方向对了!
我有这个确切的问题,然后意识到我在我的application.properties中定义了:
spring.resources.static-locations=file:/var/www/static
这压倒了我所做的一切努力。在我的情况下,我想要两者都保留,所以我只保留了财产,并添加:
spring.resources.static-locations=file:/var/www/static,classpath:static
将src/main/resources/static中的文件作为localhost:{port}/file.html。
以上这些对我来说都没用,因为没有人提到这个可以轻易从网上复制的小属性,以满足不同的目的;)
希望能有所帮助!我想它会很适合这个有这个问题的人的答案的长帖子。
与spring-boot的状态不同,要让我的spring-boot jar提供内容:
我必须通过这个配置类添加专门注册我的src/main/resources/static内容:
@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
}