初学SpringBoot--ch11-Thymeleaf 模板引擎02

1.1 表达式

表达式是在页面获取数据的一种 thymeleaf 语法。类似 ${key}

1.1.1 标准变量表达式

注意: th:text="" 是 Thymeleaf 的一个属性,用于文本的显示。

语法: ${key}
说明:标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和 EL 中的 ${} 相同。Thymeleaf 中的变量表达式使用 ${变量名} 的方式获取 Controller 中 model 其中的数据。也就是 request 作用域中的数据,使用request.setAttribute(), model.addAttribute()。

1)创建 SysUser 实体类

package com.suyv.model;

public class SysUser {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;

    public SysUser() {
    }

    public SysUser(Integer id, String name, String sex, Integer age) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    @Override
    public String toString() {
        return "SysUser{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

2)创建 Controller 类

package com.suyv.controller;

import com.suyv.model.SysUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

@Controller
@RequestMapping("/tpl")
public class ThymeleafController {

    // 标准变量表达式
    @GetMapping("/expression1")
    public String expression1(Model model){
        // 添加数据到model
        model.addAttribute("site","suyv.top");
        model.addAttribute("myuser",new SysUser(1001,"李四","男",20));
        // 指定视图
        return "expression1";
    }
}

3)创建 expression1 模板文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>标准变量表达式</title>
</head>
<body>
    <h3>标准变量表达式:${key}</h3>
    <div>
        <p th:text="${site}">11111</p><br>
        <p>获取SysUser对象、属性值</p><br>
        <p th:text="${myuser.getId()}">id</p><br>
        <p th:text="${myuser.id}">id</p><br>
        <p th:text="${myuser.getName()}">name</p><br>
        <p th:text="${myuser.getSex()}">sex</p><br>
        <p th:text="${myuser.getAge()}">age</p><br>
    </div>
</body>
</html>

4)执行测试

在这里插入图片描述

1.1.2 选择变量表达式

语法:*{key}
说明:需要配和 th:object 一起使用。选择变量表达式,也叫星号变量表达式,使用 th:object 属性来绑定对象,选择表达式首先使用 th:object 来绑定后台传来的对象,然后使用 * 来代表这个对象,后面 {} 中的值是此对象中的属性。

选择变量表达式 *{…} 是另一种类似于标准变量表达式${…}表示变量的方法。

选择变量表达式在执行时是在选择的对象上求解,而${…}是在上下文的变量 model 上求解。

1)增加 Controller 方法

	// 选择变量表达式
    @GetMapping("/expression2")
    public String expression2(Model model){
        // 添加数据到model
        model.addAttribute("site","suyv.top");
        model.addAttribute("myuser",new SysUser(1001,"李四","男",20));
        // 指定视图
        return "expression2";
    }

2)创建 expression2 模板文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>选择变量表达式</title>
</head>
<body>
    <h3>选择变量表达式:*{key}</h3>
    <div th:object="${myuser}">
        <p th:text="*{id}">id</p><br>
        <p th:text="*{name}">name</p><br>
        <p th:text="*{sex}">sex</p><br>
        <p th:text="*{age}">age</p><br>
    </div>
    <p th:text="*{myuser.name}"></p>
</body>
</html>

3)执行测试

在这里插入图片描述

1.1.3 链接表达式(URL表达式)

语法:@{链接 url}
说明:主要用于链接、地址的展示,可用于<script src="...">、<link href="...">、<a href="...">、<form action="...">、<img src="">等,可以在 URL 路径中动态获取数据。

1)增加 Controller 方法

	// 链接表达式
    @GetMapping("/link")
    public String expression3(Model model){
        model.addAttribute("userId",1002);
        model.addAttribute("name","李四");
        model.addAttribute("age",25);
        return "link";
    }
    // 测试链接表达式的地址
    @GetMapping("/queryAccount")
    @ResponseBody
    public String queryAcciunt(Integer id){
        return "queryAccount,参数id=" + id;
    }
    // 有两个参数的地址
    @GetMapping("/queryUser")
    @ResponseBody
    public String queryUser(String name,Integer age){
        return "queryUser,有两个参数:name=" + name + ",age=" + age;
    }

2)创建 link 模板文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>链接表达式</title>
</head>
<body>
    <h3>链接绝对地址</h3>
    <a th:href="@{https://www.baidu.com/}">百度</a>
    <h3>链接相对地址(无参数)</h3>
    <a th:href="@{/tpl/queryAccount}">链接相对地址,无参数</a>
    <h3>链接相对地址(一个参数)</h3>
    <a th:href="@{'/tpl/queryAccount?id=' + ${userId}}">链接相对地址,一个参数</a>
    <h3>推荐使用的传参方式(一个参数)</h3>
    <a th:href="@{/tpl/queryAccount(id=${userId})}">推荐使用的传参方式,一个参数</a>
    <h3>链接相对地址(两个参数)</h3>
    <a th:href="@{/tpl/queryUser(name=${name},age=${age})}">链接相对地址,一个参数</a>
</body>
</html>

3)执行测试

在这里插入图片描述

1.2 Thymeleaf 属性

大部分属性和 html 的一样,只不过前面加了一个 th 前缀。 加了 th 前缀的属性,是经过模版引擎处理的。在属性中可以使用变量表达式。

例如:

<form action="/loginServlet" method="post"></form>
<form th:action="/loginServlet" th:method="${methodAttr}"></form>

1.2.1 th:action

定义后台控制器的路径,类似<form>标签的 action 属性,主要结合 URL 表达式获取动态变量。

<form id="login" th:action="@{/login}" th:method="post">......</form>

1.2.2 th:method

设置请求方法。

<form id="login" th:action="@{/login}" th:method="post">......</form>

1.2.3 th:href

定义超链接,主要结合 URL 表达式,获取动态变量。

<a th:href="@{/query/student}">相对地址无参数</a>

1.2.4 th:src

用于外部资源引入,比如<script>标签的 src 属性,<img>标签的 src 属性,常与@{}表达式结合使用,在 SpringBoot 项目的静态资源都放到 resources 的 static 目录下,放到 static 路径下的内容,写路径时不需要写上 static。

<script type="text/javascript" th:src="@{/js/jquery-3.4.1.js}"></script>

1.2.5 th:text

用于文本的显示,该属性显示的文本在标签体中,如果是文本框,数据会在文本框外显示,要想显示在文本框内,使用 th:value。

<input type="text" id="realName" name="reaName" th:text="${realName}">

1.2.6 th:style

设置样式。

<a th:onclick="'fun1('+${user.id}+')'" th:style="'color:red'">点击我</a>

1.2.7 th:each

这个属性非常常用,比如从后台传来一个对象集合那么就可以使用此属性遍历输出,它与 JSTL 中的<c: forEach>类似,此属性既可以循环遍历集合,也可以循环遍历数组及 Map。

1)循环 List

a.增加 Controller 方法
	//循环 list
    @GetMapping("/eachlist")
    public String eachList(Model model){
        List<SysUser> userList =  new ArrayList<>();
        userList.add( new SysUser(1001,"张飞","男",20));
        userList.add( new SysUser(1002,"孙尚香","女",29));
        userList.add( new SysUser(1003,"韩信","男",28));
        userList.add( new SysUser(1004,"盾山","男",28));
        userList.add( new SysUser(1005,"明世隐","男",28));
        model.addAttribute("userList",userList);
        return "eachlist";
    }
b. 创建 eachlist 模板文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>循环list</title>
</head>
<body>
    <div style="margin-left: 500px">
        <h3>循环list</h3>
        <br/>
        <table border="1" cellpadding="0" cellspacing="0">
            <thead>
                <tr>
                    <td>编号</td>
                    <td>id号</td>
                    <td>姓名</td>
                    <td>性别</td>
                    <td>年龄</td>
                </tr>
            </thead>
            <tbody>
            <tr th:each="user,userStat:${userList}">
                <td th:text="${userStat.count} + '/' + ${userStat.size}"></td>
                <td th:text="${user.id}">id号</td>
                <td th:text="${user.name}">姓名</td>
                <td th:text="${user.sex}">性别</td>
                <td th:text="${user.age}">年龄</td>
            </tr>
            </tbody>
        </table>
    </div>
</body>
</html>
c.执行测试

在这里插入图片描述

2)遍历数组 Array

a.增加 Controller 方法
	//循环 Array
    @GetMapping("/eacharray")
    public String eachArray(Model model){
        SysUser[] users =  new SysUser[3];
        users[0]=  new SysUser(1001,"马超","男",22);
        users[1]=  new SysUser(1002,"黄忠","男",26);
        users[2]=  new SysUser(1003,"赵云","男",29);
        model.addAttribute("userarray",users);
        return "eacharray";
    }
b. 创建 eacharray 模板文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>循环Array</title>
</head>
<body>
    <table border="1" cellpadding="0" cellspacing="0" align="center">
        <thead>
        <tr>
            <td>编号</td>
            <td>id号</td>
            <td>姓名</td>
            <td>性别</td>
            <td>年龄</td>
        </tr>
        </thead>
        <tbody>
        <tr th:each="user:${userarray}">
            <td th:text="${userStat.count}"></td>
            <td th:text="${user.id}">id号</td>
            <td th:text="${user.name}">姓名</td>
            <td th:text="${user.sex}">性别</td>
            <td th:text="${user.age}">年龄</td>
        </tr>
        </tbody>
    </table>
</body>
</html>
c.执行测试

在这里插入图片描述

3)循环 Map

a.增加 Controller 方法
	//循环 Map
    @GetMapping("/eachmap")
    public String eachMap(Model model){
        Map<String,SysUser> map =  new HashMap<>();
        map.put("user1", new SysUser(1001,"马超","男",22));
        map.put("user2", new SysUser(1002,"黄忠","男",26));
        map.put("user3", new SysUser(1003,"赵云","男",29));
        model.addAttribute("users",map);

        //List<Map<SysUser>
        List<Map<String,SysUser>> listmap =  new ArrayList<>();

        Map<String,SysUser> map2 =  new HashMap<>();
        map2.put("sys1", new SysUser(2001,"曹操","男",22));
        map2.put("sys2", new SysUser(2002,"孙权","男",26));
        map2.put("sys3", new SysUser(2003,"刘备","男",29));

        listmap.add(map);
        listmap.add(map2);
        model.addAttribute("listmap",listmap);

        return "eachmap";
    }
b. 创建 eachmap 模板文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>循环map</title>
</head>
<body>
    <table border="1" cellpadding="0" cellspacing="0" align="center">
        <thead>
        <tr>
            <td>编号</td>
            <td>key</td>
            <td>value</td>
            <td>id号</td>
            <td>姓名</td>
            <td>性别</td>
            <td>年龄</td>
        </tr>
        </thead>
        <tbody>
        <tr th:each="map:${users}">
            <td th:text="${mapStat.count}">id号</td>
            <td th:text="${map.key}"></td>
            <td th:text="${map.value}"></td>
            <td th:text="${map.value.id}">id号</td>
            <td th:text="${map.value.name}">姓名</td>
            <td th:text="${map.value.sex}">性别</td>
            <td th:text="${map.value.age}">年龄</td>
        </tr>
        </tbody>
    </table>

    <h3>循环List Map</h3>
    <div th:each="lm:${listmap}">
        <!--循环map中的所有key,value-->
        <div th:each="m:${lm}">
            <p th:text="${m.key}"></p>
            <p th:text="${m.value.id}"></p>
            <p th:text="${m.value.name}"></p>
            <p th:text="${m.value.sex}"></p>
            <p th:text="${m.value.age}"></p>
            <hr>
        </div>
    </div>
</body>
</html>
c.执行测试

在这里插入图片描述

1.2.8 条件判断 if

语法:th:if=”boolean 条件” , 条件为 true 显示体内容。
th:unless 是 th:if 的一个相反操作。

1.2.9 switch,case 判断语句

语法:类似 java 中的 switch,case。

	<div th:switch="${sex}">
        <p th:case="m">显示男</p>
        <p th:case="f">显示女</p>
        <p th:case="*">未知</p>
    </div>

一旦某个 case 判断值为 true ,剩余的 case 则都当做 false ,“* ”表示默认的case ,前面的 case 都不匹配时候,执行默认的 case。


1)增加 Controller 方法

	@GetMapping("/ifunless")
    public String ifUnless(Model model){
        model.addAttribute("sex","m");
        model.addAttribute("isLogin", true);
        model.addAttribute("age",20);
        model.addAttribute("name","");
        return "ifunless";
    }

2)创建 ifunless 模板文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>ifUnless</title>
</head>
<body>
    <p th:if="${sex =='m'}">
        性别是男
    </p>
    <p th:unless="${sex == 'f'}">
        性别是女
    </p>
    <p th:if="${isLogin}">
        用户已经登录
    </p>
    <p th:if="${age > 50}">
        年龄是大于 50
    </p>
    <p th:if="5>0">
        5>0
    </p>
    <!-- 空字符串是 true-->
    <p th:if="${name}">
        name 是 ‘’
    </p>

    <!-- switch--case的使用-->
    <div th:switch="${sex}">
        <p th:case="m">显示男</p>
        <p th:case="f">显示女</p>
        <p th:case="*">未知</p>
    </div>
</body>
</html>

3)执行测试

在这里插入图片描述

1.2.10 th:inline

th:inline 有三个取值类型 (text, javascript 和 none)

1)内联 text

可以让 Thymeleaf 表达式不依赖于 html 标签,直接使用 内敛表达式[[ 表达式]]即可获取动态数据,要求在父级标签上加 th:inline = “text”属性。

a.增加 Controller 方法
	//内联
    @GetMapping("/inline")
    public String inline(Model model){
        model.addAttribute("sex","m");
        model.addAttribute("isLogin", true);
        model.addAttribute("age",20);
        model.addAttribute("name","明世隐");
        model.addAttribute("myuser", new SysUser(1005,"赵云","f",23));
        return "inline";
    }
b.创建 inline 模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>内联text</title>
</head>
<body>

    <div th:inline="text">
        姓名是:[[${name}]] <br/>
        登录了吗:[[${isLogin}]]
    </div>
    <br/>
    <!--不用加入 th:inline='text'-->
    <div>
        姓名是:[[${name}]] <br/>
        登录了吗:[[${isLogin}]]<br/>
        性别:[[${sex}]]
    </div>
</body>
</html>
c.执行测试

在这里插入图片描述

2)内联 javascript

可以在 js 中,获取模版中的数据。
在上面的模版页面中,增加

a.增加 JavaScript
	<script type="text/javascript" th:inline="javascript">
        var name = [[${myuser.name}]];
        var id = [[${myuser.id}]];
        function fun() {
            alert("click 用户是"+name+",他的 id 是"+id);
        }
    </script>
    
	<button onclick="fun()">单击按钮</button>
b.执行测试

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

憨憨浩浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值