Member-only story

Serving static resources with Spring WebFlux and Kotlin

Davide Cerbo
1 min readSep 23, 2019

--

When you start a WebFlux project you haven’t the support for static resources, like HTML, CSS and JS files, provided by Spring Boot project. Unfortunately how to solve this simple task isn’t so well documented, so I decided to write this post.

The simplest way I found is to define a resource router as you can see below:

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.io.ClassPathResource
import org.springframework.web.reactive.function.server.RouterFunctions.resources

@Configuration
class WebConfiguration {

@Bean
fun resRouter() = resources("/**", ClassPathResource("static/"))

}

Now you can run your application and navigate to:

http://localhost:8080/index.html

But if you try to remove the file name in the URL, you will receive a 404 error.

In order to define the file to serve as homepage, you need to define a route for the “/” path.

//...

@Bean
fun indexRouter(@Value("classpath:/static/index.html") html:
Resource) = router {
GET("/") {
ok().contentType(TEXT_HTML).syncBody(html)
}
}

//...

Now you can navigate to http://localhost:8080/ and view your static HTML page.

--

--

Davide Cerbo
Davide Cerbo

Written by Davide Cerbo

Open-space invader, bug hunter and software writer

No responses yet