thymeleaf3与springboot2的使用
向pom.xml引入依赖
1 | <dependency> |
这里一般由springboot的依赖来决定版本号。
如果手动配置版本,需要注意的是。thymeleaf 3搭配layout 2,thymeleaf 2,搭配layout 1;
默认的扫描路径
如果熟悉springBoot2自动配置的话,通过快捷键或从依赖包中打开ThymeleafProperties类,可以看到
1 | "spring.thymeleaf") (prefix = |
thymeleaf的默认规则是扫描项目路径下templates包内的html文件。
既然是一个xxxxProperties类,也就代表可以在yml/properties文件中重新设定扫描路径,如设置为public
1 | spring: |
尝试写一个页面请求
基于上面的默认扫描路径,在项目的templates文件中新建一个hello.html
1
2
3
4
5
6
7
8
9
10
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>你好!</h1>
</body>
</html>
在xxxxApplican.java所在的包下创建一个HelloControlller.java
1
2
3
4
5
6
7
8
public class HelloController {
"/hello") (
public String hello(){
return "hello";
}
}
- 启动项目访问,localhost:8080/hello
thymeleaf的语法
首先,需要在html文件的html标签中引入thymeleaf的命名空间,采用使用thymeleaf语法。1 | <html lang="en" xmlns:th="http://www.thymeleaf.org"> |
语法规则
th:
+任意html属性,都可以替换原有的html属性。如:
th:id