一、介绍

springboot更建议使用Thymeleaf作为模板引擎
springboot本身就有一个Thymeleaf的启动器

  1. <!--thymeleaf场景启动器 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  5. </dependency>

这是一个HTML模板引擎,类似于JSP
模板引擎:JSP,Thymeleaf,Freemarker….
模板引擎都是为了:用户界面和业务数据分离而产生,可以生成特定格式的文档,用于网站的模板引擎会生成一个标准的HTML文档
工作原理:(HTML模板)
image.png

SpringBoot对Thymeleaf的支持

【1】加入启动器
【2】springboot对thymeleaf的自动配置:
Thymeleaf自动配置类:自动配置类中添加Thymeleaf需要的所有Bean
image.png
属性绑定的类:
image.png
Thymeleaf模板默认放在classpath:/templates/下。后缀为.html。
也可以修改这个属性:

spring: thymeleaf: prefix: classpath:/tem/ suffix: .xml

Thymeleaf的语法

Thymeleaf中获取request作用域中的数据使用${key.attrtute}

【1】th:text和th:utext替换元素的文本内容

/**
 * @author:Cherry
 * @createTime:2021-03-30
 */
@Controller
public class ThymeleafController {

    @RequestMapping("/thy")
    public String thymeleaf(Model model){
        //简单属性
        model.addAttribute("addr","湖北省武汉市洪山区");
        model.addAttribute("size",28);
        //对象或者map
        Student student = new Student();
        student.setStuId(9527);
        student.setStuName("小樱");
        model.addAttribute("st",student);
        return "thymeleaf";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>$Title$</title>
</head>
<body>
    <ul>
        <li>简单属性:</li>
        <!--  使用th:text替换文本的内容      -->
        <li th:text="${addr}">123456</li>
        <li th:abbr="${size}">123</li>
        <li>对象属性:</li>
        <li th:text="${st.stuId}">nfjsfs</li>
        <li th:text="${st.stuName}">hgjdas</li>
    </ul>
</body>
</html>

说明:
controller的操作就是将数据放入request作用域中。
th:text属性说明:可以写在任何有内容的标签中。
-th:text=”表达式” ,表达式的内容会覆盖标签内部的文本。
-表达式就类似于EL表达式可以从request域中获取数据。

th:text和th:utext有什么区别
在request域中添加一个标签

model.addAttribute(“msg”,”

欢迎您!小丸子!

“)

html页面获取

最后界面
image.png
总结:th:text不解释运行html代码,纯文本输出
th:utext解释运行html代码

【2】简单的表达式

Literals

  • 文本: 'one text', 'Another one!',…
  • 数字: 0, 34, 3.0, 12.3,…
  • 布尔值: true, false
  • Null: null
  • Literal tokens: one, sometext, main,…

Text operations:

  • String concatenation: +
  • Literal substitutions: |The name is ${name}|

Arithmetic operations:

  • Binary operators: +, -, *, /, %
  • Minus sign (unary operator): -

Boolean operations:

  • Binary operators: and, or
  • Boolean negation (unary operator): !, not

Comparisons and equality:

  • Comparators: >, <, >=, <= (gt, lt, ge, le)
  • Equality operators: ==, != (eq, ne)
    <ul>
      <li>简单属性:</li>
      <!-- th:text:替换标签的文本内容 -->
      <li th:text="${addr}">123123</li>
      <li th:abbr="${size}">2342</li>
      <li>对象的属性值:</li>
      <li th:text="${st.stuId}">sdfsdf</li>
      <li th:text="${st.stuName}">werwer</li>
    </ul>
    <ul>
      <li th:text="${msg}"></li>
      <li th:utext="${msg}"></li>
    </ul>
    <h2>简单的表达式</h2>
    <ul>
      <li>普通的字符串:<span th:text="今天中午吃点啥">abc</span></li>
      <li>数字:<span th:text="9527"></span></li>
      <li>布尔值 : <span th:text="false"></span></li>
      <li>null:<span th:text="null"></span></li>
      <li><span th:text="abc,def,h"></span></li>
    </ul>
    <ul>
      <li>常见的运算符的运算</li>
      <li>size: <span th:text="${size + 10}"></span></li>
      <li>逻辑运算: <span th:text="${st.stuId == 9527 && size > 20}"></span></li>
      <li>字符串连接: <span th:text="${'姓名->'+st.stuName}"></span></li>
      <li>三元运算符: <span th:text="${size> 20 ?'OK':'no'}"></span></li>
    </ul>
    

【3】控制流程语句

if语句

<!-- if表达式的结果为true就显示 -->
<p th:if="${表达式}">内容</p>


案例**
准备数据:model.addAttrbute("admin",false);
页面获取:

  • 是管理员
  • 不是管理员

遍历集合

语法:th:each="prod :${prods}" ``//prod就是每一个对象,prods就是遍历的目标集合
案例
准备数据

//准备一个集合
List<Student> sts = new ArrayList<>();
for(int i = 0;i<10;i++){
    Student s = new Student();
    s.setStuId(i+1);
    s.setStuName("鸣人"+s.getStuId());
    sts.add(s);
}
model.addAttribute("sts",sts);

页面获取数据

<table align="center" width="500" border="1" cellspacing="0">
    <tr>
        <th>编号</th>
        <th>姓名</th>
    </tr>
    <tr th:each="st : ${sts}">
        <td th:text="${st.stuId}"></td>
        <td th:text="${st.stuName}"></td>
    </tr>
</table>

迭代的时候可以设置一个循环变量对象

<!-- th:each是写在要迭代的标签中的 -->
<table align="center" width="500" border="1" cellspacing="0">
    <tr>
        <th>序号</th>
        <th>编号</th>
        <th>姓名</th>
    </tr>
    <tr th:each="st,stStat : ${sts}" th:class="${stStat.odd}?'tr_color'">
        <td th:text="${stStat.index}"></td>
        <td th:text="${st.stuId}"></td>
        <td th:text="${st.stuName}"></td>
    </tr>
</table>

stStat就是循环变量对象,这个对象有属性index,从0开始,也有属性count从1开始。
属性odd,布尔类型,表示是否是偶数行。
注:stState不是特定的名字,只要在st后面使用”,”就可以添加。

【4】超链接和onclick写法

数据的列表一般都查看编辑删除等超链接,并且是动态生成的。

<th>
  <a th:href="@{inputEdit(stuId=${st.stuId},stuName=${st.stuName})}"
     href="inputEdit?stuId=${st.stuId}">编辑</a>
  <a th:href="@{'javascript:deleteStu('+${st.stuId}+')'}" href="">编辑</a>
  <a th:href="@{'stuDetail?stuId='+${st.stuId}}">查看详情</a>
</th>

【5】设置标签属性

Thymeleaf的语法是: th:xxxx
-这里的xxx就是属性名字。 前面说过的th:text。

th:href=”” 这个属性会自动替换标签中原有的href属性。
th:class=”” 会自动替换原有的class属性。

【6】Thymeleaf的内置对象

web相关的内置对象:

  • #ctx: the context object.
  • #vars: the context variables.
  • #locale: the context locale.
  • #request: (only in Web Contexts) the HttpServletRequest object.
  • #response: (only in Web Contexts) the HttpServletResponse object.
  • #session: (only in Web Contexts) the HttpSession object.
  • #servletContext: (only in Web Contexts) the ServletContext object.

以上内置对象和之前的内置对象,异曲同工。
案例:在页面使用#session取出session中的数据。
在Controller中给session添加一个数据:
image.png

  • 取出session中的数据:


案例:

1.日期
model.addAttribute("now",new Date());
页面:

日期:

2.字符串函数(java中String类的函数基本都有)
model.addAttribute("testStr","在上下文变量上计算OGNL表达式时");
页面:

3.list函数

 List<User> users = new ArrayList<User>();
        for(int i = 0;i<10;i++){
            users.add(new User(i,"鸣人"+i,18));
        }
        model.addAttribute("users",users);

页面:

th:object属性

之前:
image.png

<ul th:object="${user}">
    <li th:text="*{id}"></li>
    <li th:text="*{name}"></li>
    <li th:text="*{age}"></li>
</ul>