Thymeleaf 简介
什么是 Thymeleaf
Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点
- Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板 + 数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- Thymeleaf 开箱即用的特性。它提供标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式效果,避免每天套模板、改 JSTL、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
- Thymeleaf 提供 Spring 标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
如果希望以 Jar 形式发布模块则尽量不要使用 JSP 相关知识,这是因为 JSP 在内嵌的 Servlet 容器上运行有一些问题 (内嵌 Tomcat、 Jetty 不支持 Jar 形式运行 JSP,Undertow 不支持 JSP)。
Spring Boot 中推荐使用 Thymeleaf 作为模板引擎,因为 Thymeleaf 提供了完美的 Spring MVC 支持,Spring Boot 提供了大量模板引擎,包括:
- FreeMarker
- Groovy
- Mustache
- Thymeleaf
- Velocity
- Beetl
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-thymeleaf
net.sourceforge.nekohtml
nekohtml
1.9.22
主要增加 spring-boot-starter-thymeleaf
和 nekohtml
这两个依赖
spring-boot-starter-thymeleaf
:Thymeleaf 自动配置nekohtml
:允许使用非严格的 HTML 语法
在 application.yml
配置 Thymeleaf
spring:
thymeleaf:
#前缀,也就是模板存放的路径
prefix: classpath:/templates/
#编码格式
encoding: UTF-8
check-template-location: false
#关闭缓存,不然无法看到实时页面
cache: false
#后缀
suffix: .html
#设置不严格的html
mode: HTML
servlet:
content-type: text/html
创建测试用实体类
/**
* 部门
* @author HC
*/
public class Dept {
/**
* 部门编号
*/
private Integer deptno;
/**
* 部门名称
*/
private String dname;
/**
* 部门地址
*/
private String loc;
public Dept() {
}
public Dept(Integer deptno, String dname, String loc) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Dept{" +
"deptno=" + deptno +
", dname='" + dname + '\'' +
", loc='" + loc + '\'' +
'}';
}
}
创建测试用 Controller
创建一个 Controller,造一些测试数据并设置跳转
@Controller
@RequestMapping(value = "thymeleaf")
public class IndexController {
@RequestMapping(value = "index", method = RequestMethod.GET)
public String index(Model model) {
List depts = new ArrayList();
depts.add(new Dept(10,"ACCOUNTING","NEWYORK"));
depts.add(new Dept(20,"RESEARCH","DALLAS"));
depts.add(new Dept(30,"SALES","CHICAGO"));
depts.add(new Dept(40,"OPERATIONS","BOSTON"));
model.addAttribute("depts", depts);
return "index";
}
}
创建测试页面
在 templates
目录下创建 index.html
文件,代码如下:
Hello Thymeleaf
访问 Model:
访问列表
部门编号
部门名称
部门地址
测试访问
启动成功后,访问:http://localhost:8080/thymeleaf/index 即可看到效果