Spring Boot web开发 - Thymeleaf

227 阅读1分钟

模板引擎

Spring支持多种模板引擎,如Java Server Pages with the Java Server Pages Tag Library (JSP)/ Thymeleaf/ FreeMarker.

如下图所示,模板引擎的工作原理为:

  1. 首先写一个模板,其中动态获取的数据由${name}获取;
  2. 然后生成数据Data,之后会通过解析模板,填充进数据;
  3. 最后把模板和数据交给模板引擎处理,生成一个静态页面;

本篇介绍以Thymeleaf为模板引擎创建项目。

Thymeleaf

Spring in Action 和 Spring Boot in Action两本书都使用Thymeleaf为模板作为示例,而在前后端分离架构盛行的当下,Thymeleaf应用场景骤减。如今React和VUE框架成为前端框架的主流,通过axios发送异步请求的方式与后端交互。

使用Thymeleaf模板,首先需要引入Thymeleaf依赖,其次查看Thymeleaf的自动配置类,找mapping静态页面的原则,需要把page.html文件放置在/template下,并以html作为后缀。相关的Thymeleaf语法可以查阅Tutorial: Using Thymeleaf.

因为Thymeleaf使用频率低,本篇略过详细介绍。

Reference:

Java Template Engines

Tutorial: Using Thymeleaf