一 默认springboot的工程结构
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
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
注意:如果不引人这个依赖包,html文件应该放在比如resources、static、public这些默认的文件夹中,才可以访问。不引入这个依赖包,即便建立templates目录,下面存放页面也无法访问。
引入依赖包后,也得通过走controller后端接口代码,代码中指定跳转的页面,跳转的页面默认就会跳转到/templates/下,去访问templates下指定的页面。
注意:templates目录下的文件不可以通过页面直接访问:templates下的动态页面不能直接访问
2.文件加载顺序:
META/resources > resources > static > public 里面找是否存在相应的资源,如果有则直接返回。
当在pom.xml中引入了thymeleaf组件,动态跳转会覆盖默认的静态跳转,默认就会跳转到/templates/下。
2.springboot中static和templates区别
springboot中static和templates区别
静态页面的return默认是跳转到/static/目录下,当在pom.xml中引入了thymeleaf组件,动态跳转会覆盖默认的静态跳转,默认就会跳转到/templates/下,注意看两者return代码也有区别,动态没有html后缀。
static目录类似于传统Java web中的webroot或webcontent
1.1 在static下新建index.html
运行程序,浏览器输入http://localhost:8080/index.html
1.2 在template下新建index.html
运行程序,浏览器输入http://localhost:8080/index.html
可以看到:templates目录下的index.html并没有访问到。
访问templates目录下的test.js并没有访问到
原因是:templates下的动态页面不能直接访问
1.3 解决方法:通过接口访问
1.编写接口
2.添加依赖
3.访问
http://localhost:8080//api/v1/gopage
参考网址:springboot中static和templates的区别_CP程序员的博客-CSDN博客_springboot static template