1、目录讲解
src/main/java:存放代码
src/main/resources
static: 存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)
templates:存放静态页面jsp,html,tpl
config:存放配置文件,application.properties
resources:
2、引入依赖 Thymeleaf
Thymeleaf是用于Web和独立环境的现代服务器端Java模板引擎。
Thymeleaf的主要目标是将优雅的自然模板带到您的开发工作流程中—HTML能够在浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。Thymeleaf能够处理HTML,XML,JavaScript,CSS甚至纯文本。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
注意:如果不引人这个依赖包,html文件应该放在默认加载文件夹里面,比如resources、static、public这个几个文件夹,才可以访问
3、同个文件的加载顺序,静态资源文件
Spring Boot 默认会挨个从
META/resources > resources > static > public 里面找是否存在相应的资源,如果有则直接返回。
4、默认配置
1)官网地址:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content
2)自定义存放html等文件的文件夹,需要在application.properties文件中进行配置文件路径。
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
5、静态资源文件存储在CDN
Thymeleaf详解
例如在static中新建一个index.html后,能够在浏览器中通过http://localhost:8080/index.html访问到,但当index.html移到文件夹test中后就无法通过http://localhost:8080/index.html直接访问到了。
而引入Thymeleaf后就可以不用在意是否是springboot规定的文件夹了,通过以下这种方式来使服务器自己查找要找的页面。使用http://localhost:8080就能访问到test文件夹中的index.html文件了。
@Controller
public class SampleController {
@RequestMapping("/")
public Object home(){
return "index";
}
}
注:若@Controller变为@ResController了,网页显示的为返回内容“index”。