1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
3.Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
一个简单的测试用例:创建一个javaBean和对应的controller
User.java
package com.baiye.springboothello.entity;
public class User {
private Long id;
private String userName;
private int age;
public User() {
}
public User(Long id, String userName, int age) {
this.id = id;
this.userName = userName;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
UserController.java
package com.baiye.springboothello.controller;
import com.baiye.springboothello.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
@RequestMapping(value = "/getUserInfo",method = RequestMethod.GET)
public String getUserInfo(Model model){
User user = new User(100L,"admin",18);
User user2 = new User(101L,"李四",19);
User user3 = new User(102L,"张三",20);
User user4 = new User(103L,"王五",21);
List<User> list = new ArrayList<>();
list.add(user2);
list.add(user3);
list.add(user4);
model.addAttribute("user",user);
model.addAttribute("list",list);
return "userInfo";
}
}
userInfo.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello Thymeleaf</title>
</head>
<body>
<div>
<span>访问 Model:</span><span th:text="${user.userName}"></span>
</div>
<div>
<span>访问列表</span>
<table>
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${list}">
<td th:text="${item.id}"></td>
<td th:text="${item.userName}"></td>
<td th:text="${item.age}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
没有最终的成功,也没有致命的失败,最可贵的是继续前进的勇气…