Thymeleaf基础知识

1,103 阅读2分钟

「这是我参与11月更文挑战的第15天,活动详情查看:2021最后一次更文挑战

1. 基本内容

Thymeleaf是SpringBoot官方支持的模板引擎,有着动静分离的特点。

官方网站

Thymeleaf在线文档

1.1 模板引擎

模板引擎是为了使用户界面与业务数据分离而产生的,模板引擎可以根据需要获取对应的数据并生成特定格式的文档,极大的提高了开发效率。

如用于网站的模板引擎,即在模板引擎中将需要的数据填充进去,最终以html格式展示出来。

Java中模板引擎有:

  • Jsp,官方标准模板,老字号
  • FreeMaker
  • Velocity
  • Thymeleaf

1.2 Thymeleaf定义

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf是一个可以用于web和独立环境的现代服务器java模版引擎

Thymeleaf的特点

  • SpringBoot官方推荐,并提供了众多配置,提升使用体验和效率
  • 动静分离,以html文件为模板页,完美保留html格式语法,在没有数据填充时依然可以正常解析
  • jsp模板是以jsp文件为模板,将html改为jsp格式并添加jsp相关语法,需要服务端的访问处理jsp文件并最终返回一个html结果展示在浏览器
  • 国际化,通过配置和条件展示不同语言

MVC

Model View Controller,Thymeleaf模板引擎就充当了其中的View角色,配合Model和Controller组成Web项目架构。

动静分离

动静分离就是指静态的html模板和动态的数据是完全分离的,在没有数据时模板符合html规范,可以在浏览器解析,而获取到数据后填充到模板中形成最终的html文件解析。

2. Thymeleaf语法

设置属性: <p th:id="${user.id}">默认id值</p>

2.1 表达式

  • th::利用H5的自定义属性实现,需要支持H5,不支持时需要使用data-th:代替
  • ${...}:变量表达式,类似el表达式,获取接口绑定的变量数据
  • *{...}:选择变量表达式,通常情况下与变量表达式一致,但是当指定了变量后,可以使用选择表达式直接引用对象的属性名而不是通过对象.属性
  • #{...}:消息表达式,用于展示消息内容,也可以引用变量内容,常用于国际化
  • @{...}:链接表达式,设置超链接时使用,与th:href等标签配合
  • ~{...}:片段表达式,将重复使用的内容提取出来引用

如请求接口返回数据为user对象,对象中包含有name、age属性,则有表达式使用方式:

<!--①变量表达式,显示用户信息-->
<p th:text="${user.name}">用户名称</p>
<p th:text="${user.age}">用户年龄</p>

<!--②选择变量表达式-->
<!--和变量表达式一致时-->
<p th:text="*{user.name}">用户名称</p>
<p th:text="*{user.age}">用户年龄</p>
<!--确定变量后使用选择变量表达式-->
<div th:text="${user}">
	<p th:text="*{name}">用户名称</p>
	<p th:text="*{age}">用户年龄</p>
</div>

<!--③链接表达式,代表请求至新的url-->
<a th:href="@{indexView}">链接</a>
<!--使用变量传递url路径-->
<a th:href="@{${user.getUrl()}}">链接</a> 
<!--设置请求参数-->
<a th:href="@{getUser(id=${user.getId()})}">链接</a> 

2.2 渲染标签

  • th:id:替换标签的id属性值,
  • th:value:替换标签的value属性值,该标签通常用于input标签中,为其value属性赋值
  • th:href:替换标签的href属性值(a标签),<a th:href="@{index.html}">超链接</a>
  • th:src:替换标签的src属性值(img等标签),<script type="text/javascript" th:src="@{index.js}"></script>
  • th:text:替换标签对应的文本,如

    bigsai

  • th:utext:支持使用html的文本替换当前标签内容
  • th:object:替换标签中的对象
  • th:each:遍历变量中的值,如
  • th:if:条件语句,取值应为布尔类型,如果为false则当前标签内容不显示
  • th:unless:条件语句,取值应为布尔类型,如果为true则当前标签内容不显示
  • th:switch:条件语句,取值对应case内容,只显示对应case标签
    • th:case
    请求返回绑定user对象的集合数据,user对象包含name、age、gender等属性,此时模板页使用条件和遍历标签渲染数据有以下形式。
<!--遍历集合中对象,并获取数据-->
<tr th:each="user : ${userEntityList}">
    <td th:text="${user.getName()}">name</td>
    <td th:text="${user.getGender()}">male</td>
    <td th:text="${user.getPhone()}">13812341234</td>
</tr>

<!--条件语句标签渲染-->
<td th:if="${user.name} == 'tom'">if条件标签,姓名是tom</td>
<td th:unless="${user.name} == 'tom'">unless条件标签,姓名不是tom</td>

3. 接口定义的多种方法

3.1 HTTP请求参数的方式

/**
 * 通过http请求的方式
 * @param request
 * @return
 */
@RequestMapping("/indexHttpRequest")
public String getIndexByHttpRequest(HttpServletRequest request){
    List<UserEntity> list = new ArrayList<>();
    UserEntity userEntity = new UserEntity();
    userEntity.setName("http1");
    userEntity.setGender("male1");
    userEntity.setPhone("199807564121");
    list.add(userEntity);
    request.setAttribute("list",list);
    return "indexHttpRequest";
}

定义Thymeleaf模板并获取服务返回数据

  • 使用request的setAttribute()方法指定的字符串key获取数据
  • 由于对象存放在request属性中,获取对象自身属性时thymeleaf中会提示找不到对应的属性方法,不影响数据结果
<!--indexHttpRequest.html-->
<tr th:each="user : ${#request.getAttribute('list')}">
    <td th:text="${user.getName()}">name</td>
    <td th:text="${user.getGender()}">male</td>
    <td th:text="${user.getPhone()}">13812341234</td>
</tr>

3.2 ModelAndView的方式

/**
 * ModelAndView
 * @param
 */
@RequestMapping("/indexView")
public ModelAndView getIndexView(){
    List<UserEntity> list = new ArrayList<>();
    UserEntity userEntity = new UserEntity();
    userEntity.setName("view");
    userEntity.setGender("female");
    userEntity.setPhone("12233554466");
    list.add(userEntity);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("userList",list);
    modelAndView.setViewName("indexView");
    return modelAndView;
}

定义Thymeleaf模板并获取服务返回数据

  • controller、entity、thymeleaf组成MVC,而ModelAndView对象就是连接数据和模板的
  • 需要将数据存入ModelAndView对象中,并设置数据对应的模板名称
  • 设置完对应关系后,在模板中直接使用存储数据时使用的字符串key来获取数据
<!--indeView.html-->
<tr th:each="user : ${userList}">
    <td th:text="${user.getName()}">name</td>
    <td th:text="${user.getGender()}">male</td>
    <td th:text="${user.getPhone()}">13812341234</td>
</tr>

3.3 Mode方式

/**
 * Model
 */
@RequestMapping("/index")
public String getIndex(Model model){
    List<UserEntity> list = new ArrayList<>();
    UserEntity userEntity = new UserEntity();
    userEntity.setName("tom");
    userEntity.setGender("male");
    userEntity.setPhone("15886984");
    list.add(userEntity);
    model.addAttribute("list",list);
    return "index";
}

定义Thymeleaf模板并获取服务返回数据

  • Model模式需要在接口中传入Model对象作为参数
  • 将绑定的对象数据加入model中并以返回字符串的方式指定模板文件
  • 数据加入到Model中是可以指定key,此时使用key获取数据;如果没有指定key则使用thymeleaf规定的标准格式获取数据,如userEntityList
<!--index.html-->
<tr th:each="user : ${list}">
    <td th:text="${user.getName()}">name</td>
    <td th:text="${user.getGender()}">male</td>
    <td th:text="${user.getPhone()}">13812341234</td>
</tr>