spring-webflux-static-content
Spring WebFluxの静的コンテンツ
1. 概要
時には、Webアプリケーションで静的コンテンツを提供する必要があります。 画像、HTML、CSS、またはJavaScriptファイルの可能性があります。
このチュートリアルでは、https://www.baeldung.com/spring-webflux [Spring WebFlux]を使用して静的コンテンツを提供する方法を示します。 また、https://www.baeldung.com/spring-boot-start [Spring Boot]を使用してWebアプリケーションを構成することも想定しています。
2. デフォルト設定のオーバーライド
デフォルトでは、Spring Bootは次の場所から静的コンテンツを提供します。
-
/公
-
/静的
-
_ / resources_
-
_ / META-INF / resources_
これらのパスのすべてのファイルは、_ / [resource-file-name] _ pathの下で提供されます。
Spring WebFluxのデフォルトパスを変更する場合は、_application.properties_ファイルにこのプロパティを追加する必要があります。
spring.webflux.static-path-pattern=/assets/**
これで、静的リソースは_ / assets / [resource-file-name] _の下に配置されます。
*注意してください*これは* _ @ 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_パスの代わりに、カスタムの場所に保存された静的アセットを提供する別の方法は、https://search.maven.org/search?q = g:org.apache.maven.plugins%を使用することです20AND%20a:maven-resources-plugin [_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 URLで利用可能になります。
5. 結論
この記事では、Spring WebFluxで静的コンテンツを提供する方法を学びました。
いつものように、提示されるサンプルコードはhttps://github.com/eugenp/tutorials/tree/master/spring-5-reactive[Githubで]で入手できます。