Thymeleaf 简介
模板引擎
- 市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf
- JSP本质也是模板引擎,Spring Boot 官方推荐使用 “Thymeleaf”模板引擎
- 模板引擎原理图如下,模板引擎的作用都是将模板(页面)和数据进行整合然后输出显示,区别在于不同的模板使用不同的语法,如JSP的JSTL表达式,已经JSP自己的表达式和语法,同理Thymeleaf也有自己的语法
官方文档下载
Hello World
- 直接使用 Spring Boot 应用来学习 Thymeleaf所有语法知识,下面第一步就是新建 Spring Boot 项目,对于Spring Boot 不熟悉的可以参考《Spring Boot》
新建应用
<!-- 导入Spring Boot的thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
后台控制器
package com.lct.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
/**
* Created by Administrator on 2018/7/17 0017.
* 用户控制器
*/
@Controller
public class UserController {
/**
* 全部基于 Spring Boot给 Thymeleaf的默认配置
* 所以下面会跳转到 classpath:/templates/home.html 页面
*
* @param paramMap
* @return
*/
@RequestMapping("home")
public String goHome(Map<String, Object> paramMap) {
/** 默认Map的内容会放大请求域中,页面可以直接使用Thymeleaf取值*/
paramMap.put("name", "张三");
paramMap.put("age", 35);
return "home";
}
}
前端页面
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<h3>欢迎来到主页</h3>
<!--Thymeleaf 语法取值-->
姓名:<span th:text="${name}">未知</span>
年龄:<span th:text="${age}">未知</span>
</body>
</html>
浏览器访问测试