【问题标题】:Serving Static resources from file system | Spring Boot Web从文件系统提供静态资源 |春季引导网络
【发布时间】:2015-04-17 20:12:18
【问题描述】:

使用 Spring Boot Web 应用程序,我尝试从项目外部的文件系统文件夹中提供静态资源。

文件夹结构如下:-

          src
             main
                 java
                 resources
             test
                 java
                 resources
          pom.xml
          ext-resources   (I want to keep my static resources here)
                 test.js

弹簧配置:-

@SpringBootApplication
public class DemoStaticresourceApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(DemoStaticresourceApplication.class, args);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**").addResourceLocations("file:///./ext-resources/")
                .setCachePeriod(0);
    }
}

在我的浏览器中点击“http://localhost:9999/test/test.js”会返回 404。

我应该如何配置 ResourceHandlerRegistry 以提供上述“ext-resources”文件夹中的静态资源?

我应该能够为开发/生产环境打开/关闭缓存。

谢谢

更新 1

提供绝对文件路径有效:-

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**")
                .addResourceLocations(
                        "file:///C:/Sambhav/Installations/workspace/demo-staticresource/ext-resources/")
                .setCachePeriod(0);
}

如何提供相对位置?在构建和部署过程中,绝对路径会让我的生活变得艰难。

【问题讨论】:

  • 你试过绝对路径吗? (也许您的网址中只有一个/ :))
  • 绝对路径有效。请参阅更新的问题。有没有办法提供相对路径?
  • 构建它 :) 例如File("ext-resource").getAbsoluteFile().toURI... 检查 javadoc 的语法是否正确

标签: spring-mvc spring-boot


【解决方案1】:

file:/// 是指向文件系统根目录的绝对 URL,因此,file:///./ext-resources/ 表示 Spring Boot 正在根目录中名为 ext-resources 的目录中寻找资源。

更新您的配置以使用类似file:ext-resources/ 作为 URL。

【讨论】:

  • 仅供参考...WebMvcConfigurerAdapter 已在春季 5.0 中弃用。他们建议使用 WebMvcConfigurer 进行 mvc 配置。
  • 我会注意到路径是相对于应用程序的启动位置,而不是 jar 文件所在的位置。示例:对于 java -jar ./target/app.jar,相对路径从目标目录开始。
【解决方案2】:

这是我在 WebConfig 类的 addResourceHandlers 方法中所做的:

boolean devMode = this.env.acceptsProfiles("development");
String location;
if (devMode) {
    String currentPath = new File(".").getAbsolutePath();
    location = "file:///" + currentPath + "/client/src/";
} else {
    location = "classpath:static/";
}

【讨论】:

    【解决方案3】:

    Spring Boot Maven 插件可以向类路径添加额外的目录。在您的情况下,您可以将其包含在您的 pom 中。

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${spring.boot.version}</version>
        <configuration>
            <folders>
                <folder>${project.build.directory}/../ext-resources</folder>
            </folders>
    
            ...
        </configuration>
    </plugin>
    

    这样你就不需要在你的类中包含任何硬代码了。只需使用

    启动您的网络应用程序
    mvn spring-boot:run
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 2010-12-23
      • 1970-01-01
      相关资源
      最近更新 更多