How to Serve Static Resources in Spring Boot

Jan 24 2024
Curious how to serve static resources like JavaScript files, images or html files from spring boot app? Check this article to learn where Spring looks at for static files and also how to customize this location.

Curious how to serve static resources like JavaScript files, images or html files from spring boot app? Check this article to learn where Spring looks at for static files and also how to customize this location.

By default, Spring serves static resources from the following 4 locations on the classpath:

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

In a typical maven project structure, any content within /src/main/resources/ is already on the classpath, you need to create any of these folders there. You can also create all the four folders.

Alternatively, you can customize these locations which we will see later in this post.

Any file placed in these folders will be accessible by its name, you don’t need to mention the folder name.

Below is the maven project structure with these folders.

As you can see, we have created all 4 folders within /src/main/resources/ and created html files there with names index1.htmlindex2.htmlindex3.html and index4.html, one in each folder.

Now, if you run the application, these files will be accessible by their names. Let’s see the output.

Hit the URL: http://localhost:8080/index1.html

URL: http://localhost:8080/index2.html

URL: http://localhost:8080/index3.html

URL: http://localhost:8080/index4.html

Customize the default locations

You can customize the default resource location by a configuration property called “spring.web.resources.static-locations”. This property takes array of string which means you can provide multiple locations separated by commas. You can provide any location on the classpath or even file system.

Add the following property in application.properties file.

spring.web.resources.static-locations=classpath:/custom/

Below is our project structure.

As you can see, we created a folder called ‘custom’ on the classpath and placed index5.html file in it. Now restart the application and hit the URL.

URL: http://localhost:8080/index5.html

Note: when we customize the resource locations, the default ones will not work.