This tutorial will teach you how to configure Spring Boot so serve static resources (HTML, css, javascript) in your Web applications.
Include a Dependency that is able to serve static content
First of all, make sure you include a dependency which allows you to use HTML or static content, such as Thymeleaf:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Static Content Location
Then, you need to place static files in the appropriate location. The location where you can place static files in Spring Boot, from the highest priority to the lowest is:
- src/main/resources/resources
- src/main/resources/static
- src/main/resources/public
See for example the following structure of a Web application which serves index1.html, index2.html and index3.html from three different locations:
src ├── main │ ├── java │ │ └── com │ │ └── example │ │ └── SimpleMvcSpringBootApplication.java │ └── resources │ ├── application.properties │ ├── public │ │ └── index2.html │ ├── resources │ │ └── index3.html │ ├── static │ │ └── index1.html │ └── templates └── test └── java └── com └── example └── SimpleMvcSpringBootApplicationTests.java
Using the View Controller to map URL with resources
ViewControllerRegistry registers a View Controller. It is used when we just need to map a URL with a view using addViewController(String urlPath). This will add a view controller for the given URL. As an example, let’s say I wanted to root my login.html to /login and savepassword.html to /savepassword and, finally, my index.html to /. Here is how to do it:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/savepassword").setViewName("savepassword.html");
registry.addViewController("/login").setViewName("login.html");
registry.addViewController("/").setViewName("loggedin/index.html");
}
Accessing Javascript and css in Spring Boot
Css and javascript (.js) files are static resources and Spring Boot maps it by default in your /resources/static folder. So for example, define a file style.css file in the folder src/main/resources/static/css with a minimal content:
h1 { background-color: green; color: red; text-align: center; }
Now you can refer to your css as follows:
<html> <head> <link href="css/style.css" rel="stylesheet"> </head> <h1>Spring boot example</h1> </html>
Here is the final project structure:
├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ └── SimpleMvcSpringBootApplication.java │ │ └── resources │ │ ├── application.properties │ │ ├── static │ │ │ ├── css │ │ │ │ └── style.css │ │ │ └── index1.html │ │ └── templatesFound the article helpful? if so please follow us on Socials