本文将介绍 Spring Boot 怎样集成 Thymeleaf 模板引擎。
Thymeleaf 是一个 XML/XHTML/HTML5 模板引擎,可用于 Web 与非 Web 环境中的应用开发。它是一个开源的 Java 库,基于 Apache License 2.0 许可,由 Daniel Fernández 创建,该作者还是 Java 加密库 Jasypt 的作者。
Thymeleaf 提供了一个用于整合 Spring MVC 的可选模块,在应用开发中,你可以使用 Thymeleaf 来完全代替 JSP,或其他模板引擎,如Velocity、FreeMarker等。
Thymeleaf 的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的 XML 与 HTML 模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在 DOM(文档对象模型)上执行预先制定好的逻辑。
<!-- thymeleaf 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- spring boot web 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
在项目的 resources/application.properties 或 resources/application.yml 文件中添加如下配置:
# thymeleaf spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.check-template-location=true spring.thymeleaf.suffix=.html spring.thymeleaf.encoding=utf-8 spring.thymeleaf.servlet.content-type=text/html spring.thymeleaf.mode=HTML5 spring.thymeleaf.cache=false
在 resouces/templates 目录下面创建 index.html 模板(就是一个 HTML 文件)。模板内容如下:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring Boot Thymeleaf</title>
</head>
<body>
<table border="1">
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>电话</th>
    </tr>
    <tr  th:each="item : ${users}" >
        <td th:text="${item.id}"></td>
        <td th:text="${item.name}"></td>
        <th th:text="${item.phone}"></th>
    </tr>
</table>
</body>
</html>创建一个 UserDomain 实体类,代码如下:
public class UserDomain implements Serializable {
    private int id;
    private String name;
    private String phone;
    // 忽略 getter 和 setter
}在下面控制器的 index() 方法中返回了上面刚刚创建的 index.html 模板。代码如下:
import com.huangx.springboot.domain.UserDomain;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
@SpringBootApplication
public class SpringbootThymeleafApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootThymeleafApplication.class, args);
    }
    @RequestMapping("/")
    public String index(Map<String,Object> root) {
        // 返回数据
        List<UserDomain> userList = new ArrayList<>();
        userList.add(new UserDomain(100, "张三", "15178673344"));
        userList.add(new UserDomain(200, "李四", "15178273399"));
        userList.add(new UserDomain(300, "王五", "15178873357"));
        userList.add(new UserDomain(400, "赵六", "15178673356"));
        root.put("users", userList);
        // 指定返回模板
        return "index";
    }
}运行程序,效果图如下:

