Static Content in Spring WebFlux

1. Overview

Sometimes, we have to serve static content in our web applications. It might be an image, HTML, CSS, or a JavaScript file.

In this tutorial, we’ll show how to serve static content using Spring WebFlux. We also assume that our web application will be configured using Spring Boot.

2. Overriding the Default Configuration

By default, Spring Boot serves static content from the following locations:

  • /public
  • /static
  • /resources
  • /META-INF/resources

All files from these paths are served under the /[resource-file-name] path.

If we want to change the default path for Spring WebFlux, we need to add this property to our application.properties file:

spring.webflux.static-path-pattern=/assets/**

Now, the static resources will be located under /assets/[resource-file-name].

Please note that this won’t work when the @EnableWebFlux annotation is present.

3. Routing Example

It’s also possible to serve static content using the WebFlux routing mechanism.

Let’s look at an example of a routing definition to serve the index.html file:

@Bean
public RouterFunction<ServerResponse> htmlRouter(
  @Value("classpath:/public/index.html") Resource html) {
    return route(GET("/"), request
      -> ok().contentType(MediaType.TEXT_HTML).syncBody(html)
    );
}

We can also serve static content from custom locations with the help of RouterFunction.

Let’s see how to serve images from the src/main/resources/img directory using the /img/** path:

@Bean
public RouterFunction<ServerResponse> imgRouter() {
    return RouterFunctions
      .resources("/img/**", new ClassPathResource("img/"));
}

4. Custom Web Resources Path Example

Another way to serve static assets stored in custom locations, instead of the default src/main/resources path, is to use the maven-resources-plugin and an additional Spring WebFlux property.

First, let’s add the plugin to our 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>

Then, we simply need to set the static locations property:

spring.resources.static-locations=classpath:/assets/

After these actions, the index.html will be available under the http://localhost:8080/index.html URL.

5. Conclusion

In this article, we learned how to serve static content in Spring WebFlux.

As always, the sample code presented is available over on GitHub.

Related posts:

Spring Boot - Scheduling
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Spring Boot - Eureka Server
SOAP Web service: Authentication trong JAX-WS
A Guide to EnumMap
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Giới thiệu Google Guice – Injection, Scope
Java Program to Describe the Representation of Graph using Adjacency List
Upload and Display Excel Files with Spring MVC
Hướng dẫn Java Design Pattern – Command
Tính đóng gói (Encapsulation) trong java
New Features in Java 11
Zipping Collections in Java
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Java Program to Implement Range Tree
Java Program to Find Basis and Dimension of a Matrix
How to Delay Code Execution in Java
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
Java – Try with Resources
Copy a List to Another List in Java
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Guide to Spring @Autowired
Java Program to Implement the RSA Algorithm
Object cloning trong java
Java Program to Implement Disjoint Sets
Java Program to Implement Triply Linked List
Exploring the Spring Boot TestRestTemplate
Java Program to Implement Quick Sort with Given Complexity Constraint
Functional Interface trong Java 8
Java Program to Implement Doubly Linked List