1. 概要

場合によっては、Webアプリケーションで静的コンテンツを提供する必要があります。 画像、HTML、CSS、またはJavaScriptファイルの場合があります。

このチュートリアルでは、 SpringWebFluxを使用して静的コンテンツを提供する方法を示します。 また、Webアプリケーションは SpringBootを使用して構成されることを前提としています。

2. デフォルト構成のオーバーライド

デフォルトでは、SpringBootは次の場所から静的コンテンツを提供します。

  • /公衆
  • /静的
  • /資力
  • / META-INF / resources

これらのパスのすべてのファイルは、 /[resource-file-name]パスで提供されます。

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 パスの代わりに、カスタムの場所に保存されている静的アセットを提供する別の方法は、maven-resources-pluginと追加のSpringWebFluxプロパティを使用することです。

まず、プラグインを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.htmlhttp:// localhost:8080 / index.htmlURLで利用できるようになります。

5. 結論

この記事では、SpringWebFluxで静的コンテンツを提供する方法を学びました。

いつものように、提示されたサンプルコードはGitHubから入手できます。