Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:


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 file:


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:

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:

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:


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


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.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!