开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第17天,点击查看活动详情
Springboot整合Thymeleaf引擎
Thymeleaf引擎介绍
Thymeleaf是一款Java模版引擎,支持html、xml、JavaScript、CSS、纯文本等,可以将html在浏览器中正确显示,如果直接打开html,浏览器会忽略Thymeleaf标签,展示html的静态效果,如果是通过web应用程序访问,会将Thymeleaf标签的内容动态进行替换,展示动态页面。
Thymeleaf语法介绍
命名空间
html页面中需要声明命名空间xmlns:th="www.thymeleaf.org",但是可以不声明,不影响Thymeleaf的使用,但是避免编辑器出现html验证错误,推荐使用命名空间。
简单表达式
| 语法 | 描述 |
|---|---|
| ${} | 取出上下文中的变量值 |
| *{} | 取出选择对象的属性值,用于获取对象的属性值 |
| #{} | 消息表达式,用于文字消息国际化 |
| @{} | 用于表示各种超链接地址 |
| ~{} | 引用一段公共的代码片段 |
使用文本
- th:text 默认会对含有html标签的内容进行转义
- th:utext 不会对含有html标签的内容进行转义
条件判断
- th:if
- th:unless 和th:if相反,结果为假时显示。
- th:switch switch-case效果,需要搭配th:case使用。
还有很多语法规则,感兴趣的同学可以自己试试,包括字面值、算术运算、布尔运算、属性值、遍历、注释、定义局部变量、内联表达式等等。
Springboot整合Thymeleaf
-
增加maven依赖,在pom文件中Thymeleaf的依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> -
增加Thymeleaf配置,在application.yml中增加配置。
spring: thymeleaf: cache: false # 关闭缓存 -
Thymeleaf模版引擎默认会读取resources目录下面的templates目录,所以我们需要在resources目录下面建立templates目录,这个可以在上方的yml文件中修改,修改引擎读取的路径。
-
在controller层中新建IndexController.java,方法的返回值为index。
@Controller @RequestMapping("/test") public class TestController { @RequestMapping("/index") public String index(Model model) { model.addAttribute("message", "Test"); return "index"; } } -
在templates目录下新建index.html,index对应controller层中方法返回的字符串。
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>TestThymeleaf</title> </head> <body> <span th:text="${message}"></span> </body> </html> -
启动项目,在浏览器中输入http://localhost:端口/test/index即可。