How to Serve Static Resources in Spring Boot

May 28 20222 min read
How to Serve Static Resources in Spring Boot

Spring boot offers few default locations that can be used to place static resources. These locations can be overridden by supplying a property in application.properties file.

Default locations

Spring serves static resources from the following 4 locations on the classpath.

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

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

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.

We have created all 4 folders within /src/main/resources/ and placed 4 html files in there, one in each folder. These files contain their path from the project root.

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

Override the default locations

You can customize the default resource location by a configuration property called “spring.web.resources.static-locations”. This property takes an 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.

Note: The default locations won’t work once you override it.

We create a folder called custom on the classpath and add the following property in application.properties file.

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

Below is our project structure.

Now place index5.html file in it and restart the application and hit the URL.

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