Serve Static Resources with Spring Boot
In this tutorial we show how Spring Boot serves static resources like (html, js, css) in a web application.
1- Default path for static resources
By default Spring Boot serves static resources defined under the following paths:
- /META-INF/resources/
- /resources/
- /static/
- /public/
Except for index.html which is served as the root resource when accessing the root URL of a Spring Boot application, this page need not exist under the above paths.
In order to change the default paths of static resources, you can define “spring.resources.static-locations” attribute under application.properties as the following:
1 | spring.resources.static-locations=/html/,/js/,/css/ |
2- Welcome page
By default, Spring boot serves index.html as the root resource when accessing the root URL of a web application.
In order to define your own root resource, you can map the root path ‘/’ inside your controller and return your own html as the following:
1 2 3 4 5 6 7 8 | @Controller public class HomeController { @RequestMapping("/") public String welcome(Map<String, Object> model) { return "home.html"; } } |
home.html should exist under any of these paths:
- src/main/resources/META-INF/resources/home.html
- src/main/resources/resources/home.html
- src/main/resources/static/home.html
- src/main/resources/public/home.html
3- Serve HTML files from Controller
In order to return an HTML view from a controller, you need to return its full name plus the extension knowing that it’s located under any of the paths defined in step-1.
Here below we map /home URL to load home.html view:
1 2 3 4 | @RequestMapping("/home") public String home(Map<String, Object> model) { return "home.html"; } |
how to add a model attribute to the page?