1. 概述
有時,我們需要在我們的 Web 應用程序中提供靜態內容。這可能包括圖像、HTML、CSS 或 JavaScript 文件。
在本教程中,我們將演示如何使用 Spring WebFlux 提供靜態內容。我們還假設我們的 Web 應用程序將使用 Spring Boot 進行配置。
2. 覆蓋默認配置
默認情況下,Spring Boot 從以下位置提供靜態內容:
- /public
- /static
- /resources
- /META-INF/resources
所有這些路徑上的文件都位於 /[資源文件名稱] 路徑下提供。
為了更改 Spring WebFlux 的默認路徑,我們需要將以下屬性添加到我們的 application.properties 文件中:
spring.webflux.static-path-pattern=/assets/**現在,靜態資源將位於 /assets/[資源文件名] 下。
請注意,當存在 @EnableWebFlux 註解時,此方法將不起作用。
3. 路由示例
還可以使用 WebFlux 路由機制來提供靜態內容。
下面是一個路由定義示例,用於提供 index.html 文件:
@Bean
public RouterFunction<ServerResponse> htmlRouter(
@Value("classpath:/public/index.html") Resource html) {
return route(GET("/"), request
-> ok().contentType(MediaType.TEXT_HTML).syncBody(html)
);
}我們還可以使用 RouterFunction 服務靜態內容,從自定義位置提供內容。
讓我們看看如何使用 /img/** 路徑從 src/main/resources/img 目錄中提供圖像:
@Bean
public RouterFunction<ServerResponse> imgRouter() {
return RouterFunctions
.resources("/img/**", new ClassPathResource("img/"));
}4. 自定義 Web 資源路徑示例
除了使用默認的 src/main/resources 路徑之外,另一種為存儲在自定義位置的靜態資源提供服務的做法,是使用 maven-resources-plugin 插件以及額外的 Spring WebFlux 屬性。
首先,讓我們將插件添加到我們的 pom.xml 中:
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/assets</directory>
<filtering>true</filtering>
</resource>
</resources>
<outputDirectory>${basedir}/target/classes/assets</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
然後,我們只需要設置靜態位置屬性:
spring.resources.static-locations=classpath:/assets/在執行完這些操作後,index.html 將在 http://localhost:8080/index.html 網址下提供。
結論
本文介紹瞭如何在 Spring WebFlux 中提供靜態內容。