1. Directory structure
1.src/main/java: store Java code
2.src/main/resources
- resources: (Spring Boot default) to store resource files
- static: (Spring Boot default) to store static files, such as css, js, image, (access http://localhost:8080/js/main.js)
- public: (Spring Boot default) to store public files
- templates: (user-defined, you can name it arbitrarily, but the recognized file name is used here) to store static pages, such as jsp, html
- config: (user-defined, you can name it anything you want, but the recognized file name is used here) to store configuration files, such as application.properties
2. Loading sequence of the same file, static resource file
Spring Boot from the default one by one META/resources > resources > static > public
to find whether there exist appropriate resources, if there is a direct return.
For example: Let's create a new js file in these folders, and see which file it will load?
Enter the following address in the address bar: http://localhost:8080/test.js, here we did not build the test.js file under the resources folder, so we will load the files under the static folder
Three, templates folder
Files in the templates folder need to be forwarded to be accessible
Because templates is not the Spring Boot default folder, we cannot access the files in this folder
1. To access, you need to introduce dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. Write a controller
@Controller
public class jumpController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
3.Thymeleaf configuration file (configured in application.properties)
#####Thymeleaf配置文件
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
#编码
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.check-template=true
#类型
spring.thymeleaf.servlet.content-type=text/html
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#后缀
spring.thymeleaf.suffix=.html
At this time, localhost:8080/index
you can access index.html under templates
Four, define the loading order yourself or add your own new folder
Edit application.properties
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
Official website description:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content