1.springBoot引入thymleaf引擎模板
首先看一下整个项目的最终的结构
在pom.xml文件中引入thymeleaf依赖即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
下面需要在resources目录下创建templates目录,并在该目录下写html文件,这个模板就会起作用。
因为在springBoot默认配置中默认寻找templates文件夹下的html文件,下面在Controller文件下写一个Controller类进行测试。
@Controller
public class HelloController {
//访问localhost:8080/hello,返回字符串
@ResponseBody
@RequestMapping("/hello")
public String Hello(){
return "Hello World";
}
//访问localhost:8080/index,会返回templates/projectTemplates/下的index.html文件
@RequestMapping("/index")
public String Index(){
return "projectTemplates/index";
}
}
index.html如下:其中xmlns:th="http://www.thymeleaf.org"为命名空间,作用主要是提示thymeleaf语法。
<!DOCTYPE html>
<!--xmlns:th="http://www.thymeleaf.org"作用主要是提示thymeleaf语法-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
<script src="../projectResources/js/first.js" type="text/javascript"></script>
<link rel="stylesheet" href="../projectResources/css/first.css" type="text/css"/>
</head>
<body>
<h1>欢迎页面</h1>
<div id = "firstImage"></div>
</body>
</html>
最终结果如下:
2.springBoot对静态资源的映射规则
访问当前项目的任何资源,都会找相应的静态资源文件夹映射,对应的静态文件夹一般创建在resources目录下。
1)第一个静态文件夹:/META-INF/resources
2)第二个静态文件夹:/public
3)第三个静态文件夹:/static
4)第四个静态文件夹:/resources
当我们使用localhost:8080/xxx时,springBoot项目会去上述四个静态文件夹找,如果没有,则会报错。假如我们在/static下又创建一个文件夹,例如:/static/images/1.png。则我们使用localhost:8080/images/1.png就可以访问。例如图1的目录结构图:在4个静态文件下均写了4个文件进行测试。
测试1:
测试2:
测试3:
测试4:
上述测试可以看出,项目会直接访问静态文件夹下的文件。
3.注意事项
对于SpringBoot,上述四个静态文件夹和templates文件夹之间是透明的,什么意思呢?
对于index.html文件去引用css文件,则需要"…/projectResources/css/first.css",
而不是"…/…/static/projectResources/css/first.css"。相当于/META-INF/resources、/public、/static、/resources和/templates平级且每个文件夹的文件访问没有任何障碍。这一点在写WEB项目时,静态资源之间的引用可以体现出来。