我无法让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)


当前回答

我在spring boot 2.1.3中也遇到了同样的问题,说资源没有找到404。我从application .properties中删除了下面的内容。

#spring.resources.add-mappings=true
#spring.resources.static-locations=classpath:static
#spring.mvc.static-path-pattern=/**,

删除了@enableWebMVC,并删除了任何WebMvcConfigurer覆盖

@EnableWebMvc

还要确保在配置中有@EnableAutoConfiguration。

然后把所有的静态资源放到src/main/resources/static中,它就像魔术一样最终工作了。

其他回答

你检查Spring Boot参考文档了吗?

默认情况下,Spring Boot将从类路径中的/static(或/public或/resources或/META-INF/resources)文件夹或ServletContext的根目录中提供静态内容。

您还可以将您的项目与Spring MVC服务Web内容指南进行比较,或者查看Spring -boot-sample- Web -ui项目的源代码。

这个解决方案对我来说很有效:

首先,在webapp/WEB-INF下放置一个资源文件夹,如下图所示

-- src
  -- main
    -- webapp
      -- WEB-INF
        -- resources
          -- css
          -- image
          -- js
          -- ...

第二,在spring配置文件中

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter{

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resource/**").addResourceLocations("WEB-INF/resources/");
    }
}

然后,您可以访问您的资源内容,例如 http://localhost:8080/resource/image/yourimage.jpg

将静态资源放在目录下:

/src/main/resources/static

在应用程序中添加此属性。属性文件

server.servlet.context-path=/pdx

您可以从http://localhost:8080/pdx/images/image.jpg访问

我在spring boot 2.1.3中也遇到了同样的问题,说资源没有找到404。我从application .properties中删除了下面的内容。

#spring.resources.add-mappings=true
#spring.resources.static-locations=classpath:static
#spring.mvc.static-path-pattern=/**,

删除了@enableWebMVC,并删除了任何WebMvcConfigurer覆盖

@EnableWebMvc

还要确保在配置中有@EnableAutoConfiguration。

然后把所有的静态资源放到src/main/resources/static中,它就像魔术一样最终工作了。

如果从IDE中启动应用程序时出现问题(即从Eclipse或IntelliJ Idea启动),并使用Maven,解决方案的关键在Spring-boot Getting Started文档中:

如果你正在使用Maven,执行: MVN包&& Java -jar target/gs-spring-boot-0.1.0.jar

其中重要的部分是添加要在应用程序实际启动之前运行的包目标。(想法:运行菜单,编辑配置…,添加,然后选择运行Maven目标,并在字段中指定包目标)