likes
comments
collection
share

SpringBoot与Thymeleaf模板入门整合篇

作者站长头像
站长
· 阅读数 22

11.1 认识 Thymeleaf Thymeleaf 是一个流行的模板引擎,该模板引擎采用 Java 语言开发 模板引擎是一个技术名词,是跨领域跨平台的概念,在 Java 语言体系下有模板引擎,在 C#、PHP 语言体系下也有模板引擎,甚至在 JavaScript 中也会用到模板引擎技术,Java 生态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。 Thymeleaf 对网络环境不存在严格的要求,既能用于 Web 环境下,也能用于非 Web 环境下。在非 Web 环境下,他能直接显示模板上的静态数据;在 Web 环境下,它能像 Jsp 一样从后台接收数据并替换掉模板上的静态数据。它是基于 HTML 的,以 HTML 标签为载体,Thymeleaf 要寄托在 HTML 标签下实现。 SpringBoot 集成了 Thymeleaf 模板技术,并且 Spring Boot 官方也推荐使用 Thymeleaf 来替代 JSP 技术,Thymeleaf 是另外的一种模板技术,它本身并不属于 Spring Boot,Spring Boot只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的 Java Web 开发中,我们往往会选择使用 Jsp 去完成页面的动态渲染,但是 jsp 需要翻译编译运行,效率低 Thymeleaf 的官方网站:www.thymeleaf.org Thymeleaf 官方手册:www.thymeleaf.org/doc/tutoria… 11.2 SpringBoot集成 Thymeleaf 11.2.1 新建一个springboot项目,项目名称:037-springboot-thymeleaf-first 创建 Spring Boot 项目,添加 web 和 Thymeleaf 依赖\

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

按照这种方式创建后,pom.xml  文件下会自动添加如下依赖

<!--SpringBoot 集成 Thymeleaf 的起步依赖-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--SpringBoot 开发 web 项目的起步依赖-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

11.2.2 在Springboot的核心配置文件application.properties中对Thymeleaf进行配置

#thymeleaf 页面的缓存开关,默认 true 开启缓存
#建议在开发阶段关闭 thymeleaf 页面缓存,目的实时看到页面
spring.thymeleaf.cache=false

其实什么都不用配置就可以工作,因为基本 Thymeleaf 的配置都有默认值

#前缀:
#thymeleaf 模版前缀,默认可以不写
spring.thymeleaf.prefix=classpath:/templates/
#后缀:
#thymeleaf 模版后缀,默认可以不写
spring.thymeleaf.suffix=.html

11.2.3 创建 ThymeleafControlle去映射到模板页面(和 SpringMVC基本一致)

@Controller
public class ThymeleafController {
@RequestMapping(value = "/thymeleaf/index")
public String index(Model model) {
        model.addAttribute("data","SpringBoot 成功集成 Thymeleaf 模版!");
        return "index";
    }
}

11.2.4 在src/main/resources 的templates  下新建一个 index.html页面用于展示数据

HTML 页面的元素中加入以下属性:

 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>SpringBoot 集成 Thymeleaf</title>
</head>
<body >
  <!--Thymeleaf 前端框架以 Html 为载体-->
  <span th:text="${data}"></span>
  <span th:text="${data}"></span>
  <p th:text="${data}"></p>
  <div th:text="${data}"></div>
</body>
</html>

11.2.5 启动程序,

SpringBoot与Thymeleaf模板入门整合篇

右键->查看页面源代码

SpringBoot与Thymeleaf模板入门整合篇

注 意 : Springboot 用 使 用 thymeleaf  作 为 视 图 展 示 , 约 定 将 模 板 文 件 放 置 在src/main/resource/templates  目录下,静态资源放置在 src/main/resource/static  目录下

11.3 Thymeleaf 的表达式

11.3.6 新建一个springboot项目,项目名称:038-springboot-thymeleaf-expression

1)创建SpringBoot的web项目并使用模版引擎

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

2)pom.xml中应该有如下两个依赖

    <!--SpringBoot 集成 Thymeleaf 模版引擎的起步依赖-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--SpringBoot 的 web 项目起步依赖-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3)在 application.properties中设置 thymeleaf 参数

 #设置 thymeleaf 页面缓存失效
spring.thymeleaf.cache=false
#thymeleaf 模版前缀,默认值,可选项
spring.thymeleaf.prefix=classpath:/templates/
#thymeleaf 模版后缀,默认值,可选项
spring.thymeleaf.suffix=.html

4)创建实体 User 实体类

创建 User 实体类,为后续演示提供数据

@Data
public class User {
    private Integer id;
    private String name;
    private String phone;
    private String address;
}

5)创建 ThymeleafController 类

@Controller
public class ThymeleafController {
    @RequestMapping(value = "/thymeleaf/index")
    public String index(Model model) {
        model.addAttribute("data","SpringBoot 集成 Thymeleaf 模版!");
        return "index";
    }
}

6)在src/main/resources/templates 在创建 html 页面

    <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Thymeleaf'Index</title>
</head>
<body>
	<span th:text="${data}"></span>
</body>
</html>

7)测试

SpringBoot与Thymeleaf模板入门整合篇

11.3.7 标准变量表达式 注意:th:text="" 是Thymeleaf 的一个属性,用于文本的显示 8)语法 ... 9)说明 标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和EL中的{...}\ 9)说明\ 标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和 EL 中的 ... 9)说明 标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和EL中的{} 相同。Thymeleaf 中的变量表达式使用 ${变量名} 的方式获取 Controller 中 model 其中的数据 10)案例演示 创建一个方法,将用户信息存放到 model 中,thymeleaf 模版页面获取对象信息 ●在 ThymeleafController 中添加方法,向 model 放入 User 对象

    @RequestMapping(value = "/thymeleaf/user")
public String user(Model model) {
  User user = new User();
  user.setId(1);
  user.setName("张三");
  user.setPhone("13700000000");
  user.setAddress("北京市亦庄经济开发区");
  model.addAttribute("user",user);
  return "user";
}
  • 在 templates 目录下创建 user.html 页面获取 User 对象数据
    <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>展示用户对象信息</title>
</head>
<body>
  <h2>展示 User 用户信息:</h2>
  用户编号:<span th:text="${user.id}"></span><br/>
  用户姓名:<span th:text="${user.name}"></span><br/>
  用户手机号:<span th:text="${user.phone}"></span><br/>
  用户地址:<span th:text="${user.address}"></span><br/>
</body>
</html>

SpringBoot与Thymeleaf模板入门整合篇

### 11.3.8 选择变量表达式 选择变量表达式 (了解,不推荐使用)

11)语法:*{...}

12)说明

选择变量表达式,也叫星号变量表达式,使用 th:object 属性来绑定对象

选择表达式首先使用 th:object 来绑定后台传来的 User 对象,然后使用 * 来代表这个对象,后面 {} 中的值是此对象中的属性。

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

选择变量表达式在执行时是在选择的对象上求解,而${...}是在上下文的变量 Model 上求解,这种写法比标准变量表达式繁琐,只需要大家了解即可

13)案例演示

  • 在 user.html 通过选择变量表达式(星号表达式)获取用户数据

    <h2>展示 User 用户信息(星号表达式,仅在 div 范围内有效):</h2>
  <div th:object="${user}">
  用户编号:<span th:text="*{id}"></span><br/>
  用户姓名:<span th:text="*{name}"></span><br/>
  用户手机号:<span th:text="*{phone}"></span><br/>
  用户地址:<span th:text="*{address}"></span><br/>
</div>
-   浏览器访问 http://localhost:8080/thymeleaf/ user 测试

SpringBoot与Thymeleaf模板入门整合篇

11.3.9 标准变量表达式和选择变量表达式混合使用

标准变量和选择变量表达式可以混合使用,也可以不混合使用,使用 th:object 进行对象的选择,也可以直接使用 *{...} 获取数据

在 user.html 模版中添加如下代码:

    <h2>标准变量表达式和选择变量表达式混用</h2>
<h3>=======标准变量表达式=======</h3>
用户编号:<span th:text="${user.id}"></span><br/>
用户姓名:<span th:text="${user.name}"></span><br/>
用户手机号:<span th:text="${user.phone}"></span><br/>
用户地址:<span th:text="${user.address}"></span><br/>
<h3>=======选择变量表达式=======</h3>
用户编号:*{user.id} ==> <span th:text="*{user.id}"></span><br/>
用户姓名:*{user.name} ==> <span th:text="*{user.name}"></span><br/>
用户手机号:*{user.phone} ==> <span th:text="*{user.phone}"></span><br/>
用户地址:*{user.address} ==> <span th:text="*{user.address}"></span><br/>
  • 测试查看结果

SpringBoot与Thymeleaf模板入门整合篇

11.3.10 URL 表达式

14)语法@{...}

15)说明

主要用于链接、地址的展示,可用于

    
这种方式比传统方式的好处是,在 URL 表达式前加/,会自动加上上下文根,避免 404 找不到资源的情况。
11.4.6 th:id\
类似 html 标签中的 id 属性
<span th:id="${hello}">aaa</span>
11.4.7 th:name
设置名称
<input th:type="text" th:id="userName" th:name="userName">\
11.4.8 th:value
类似 html 标签中的 value 属性,能对某元素的 value 属性进行赋值\
<input type="hidden" id="userId" name="userId" th:value="${userId}">\
11.4.9 th:attr
该属性也是用于给 HTML 中某元素的某属性赋值,好处是可以给 html 中没有定义的属性动态的赋值。

    
    

th:attr 属性的使用

```

SpringBoot与Thymeleaf模板入门整合篇

11.4.10 th:text

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

11.4.11 th:object

用于数据对象绑定

通常用于选择变量表达式(星号表达式)

11.4.12 th:onclick

    <h1>th:onclick 的使用</h1>
<!--目前 thymeleaf 版本要求只能传递数字和布尔值-->
<a th:onclick="'show('+${user.id}+')'">点击:显示学生编号</a>
<script type="text/javascript">
  function show(id) {
  	alert("用户编号为:" + id);
  }
</script>

11.4.13 th:style

设置样式

    <a th:onclick="'show('+${user.id}+')'" th:style="'font-size:40px;color:red;'">点击:显示学生编号</a>
11.4.14 *th:each

这个属性非常常用,比如从后台传来一个对象集合那么就可以使用此属性遍历输出,它与JSTL 中的<c: forEach>类似,此属性既可以循环遍历集合,也可以循环遍历数组及 Map 28)遍历List集合 A、在 ThymeleafController  中添加 eachList  方法,准备集合数据

@RequestMapping("/each/list")
public String eachList(Model model){
    List<User> userList = new ArrayList<User>();
    for (int i = 0;i < 10;i++){
    User user = new User();
    user.setId(100 + i);
    user.setNick("张" + i);
    user.setPhone("1361234567" + i);
    user.setAddress("北京市大兴区" + i);
    userList.add(user);
    }
    model.addAttribute("userList",userList);
    return "each";
}

B、创建 eachList.html 对 List 集合进行遍历

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>循环遍历 List 集合</title>
</head>
<body>
  <h1>th:each 循环遍历 List 集合</h1>
  <div style="color: red">
    1.user:当前对象的变量名<br/>
    2.userStat:当前对象的状态变量名<br/>
    3.${userList}:循环遍历的集合<br/>
    4.变量名自定义
  </div>
  <div th:each="user,userStat:${userList}">
    <span th:text="${userStat.index}"></span>
    <span th:text="${user.id}"></span>
    <span th:text="${user.name}"></span>
    <span th:text="${user.phone}"></span>
    <span th:text="${user.address}"></span>
  </div>
</body>
</html>

代码说明

th:each="user, iterStat : userlist"中的{userlist}" 中的 userlist"中的{userList}  是后台传过来的集合

◼  user

定义变量,去接收遍历${userList}集合中的一个数据

◼  iterStat

${userList} 循环体的信息

◼  其中 user 及 iterStat 自己可以随便取名

◼  interStat 是循环体的信息,通过该变量可以获取如下信息

index:  当前迭代对象的 index (从 0  开始计算)

count:  当前迭代对象的个数(从 1  开始计算) 这两个用的较多

size: 被迭代对象的大小

current: 当前迭代变量

even/odd: 布尔值,当前循环是否是偶数/奇数(从 0 开始计算)

first: 布尔值,当前循环是否是第一个

last: 布尔值,当前循环是否是最后一个

注意:循环体信息 interStat  也可以不定义,则默认采用迭代变量加上 Stat  后缀,即 userStat

C、浏览器 访问测试

SpringBoot与Thymeleaf模板入门整合篇

29)遍历Map集合

D、在 ThymeleafController 中添加 eachMap  方法

@RequestMapping(value = "/each/map")
public String eachMap(Model model) {
    Map<Integer,Object> userMaps = new HashMap<Integer, Object>();
    for (int i = 0; i < 10; i++) {
        User user = new User();
        user.setId(i);
        user.setName("李四"+i);
        user.setPhone("1390000000"+i);
        user.setAddress("天津市"+i);
        userMaps.put(i,user);
    }
    model.addAttribute("userMaps",userMaps);
    return "eachMap";
}

E、添加 eachMap.html页面对Map集合进行遍历

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>循环遍历 Map 集合</title>
</head>
<body>
  <h1>th:each 循环遍历 Map 集合</h1>
  <div th:each="userMap,userMapStat:${userMaps}">
    <span th:text="${userMapStat.count}"></span>
    <span th:text="${userMap.key}"></span>
    <span th:text="${userMap.value}"></span>
    <span th:text="${userMap.value.id}"></span>
    <span th:text="${userMap.value.name}"></span>
    <span th:text="${userMap.value.phone}"></span>
    <span th:text="${userMap.value.address}"></span>
  </div>
</body>
</html>

代码说明

th:each="userMap,userMapStat:${userMaps}" ,用 userMap 变量接收每次遍历的结果,封装

为一个键值对,userMapStat 状态

userMap.key:获取当前键值对中的 key

userMap.value:获取当前键值对中的 value

F、浏览器访问测试

SpringBoot与Thymeleaf模板入门整合篇

30)遍历Array数组

G、在 ThymeleafController  中的 eachArray  方法中准备数组数据

@RequestMapping(value = "/each/array")
public String eachArray(Model model) {
    User[] userArray = new User[10];
    for (int i = 0; i < 10; i++) {
        User user = new User();
        user.setId(i);
        user.setName("赵六"+i);
        user.setPhone("1380000000"+i);
        user.setAddress("深圳市"+i);
        userArray[i] = user;
    }
    model.addAttribute("userArray",userArray);
    return "eachArray";
}

H、在 eachArray.html  页面对数组进行遍历(和 List  一样)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>循环遍历 Array 数组</title>
</head>
<body>
  <div th:each="user,userStat:${userArray}">
    <span th:text="${userStat.count}"></span>
    <span th:text="${user.id}"></span>
    <span th:text="${user.name}"></span>
    <span th:text="${user.phone}"></span>
    <span th:text="${user.address}"></span>
  </div>
</body>
</html>

I、浏览器访问测试

SpringBoot与Thymeleaf模板入门整合篇

31)比较复杂的循环案例

求:List  里面放 Map ,Map  里面又放的是 List

SpringBoot与Thymeleaf模板入门整合篇

J、在 ThymeleafController 的 each  方法中构造数据

@RequestMapping(value = "/each/all")
public String eachAll(Model model) {
    //list -> Map -> List -> User
    List<Map<Integer,List<User>>> myList = new ArrayList<Map<Integer,
    List<User>>>();
    for (int i = 0; i < 2; i++) {
        Map<Integer,List<User>> myMap = new HashMap<Integer,
        List<User>>();
        for (int j = 0; j < 2; j++) {
            List<User> myUserList = new ArrayList<User>();
            for (int k = 0; k < 3; k++) {
                User user = new User();
                user.setId(k);
                user.setName("张三"+k);
                user.setPhone("1350000000"+k);
                user.setAddress("广州市"+i);
                myUserList.add(user);
            }
            myMap.put(j,myUserList);
        }
        myList.add(myMap);
    }
    model.addAttribute("myList",myList);
    return "eachAll";
}

K、在 eachAll.html  页面对复杂集合关系进行遍历

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<title>循环遍历复杂集合</title>
</head>
<body>
  <h1>循环遍历复杂集合:list -> Map -> List -> User</h1>
  <div th:each="myListMap:${myList}">
    <div th:each="myListMapObj:${myListMap}">
      Map 集合的 key:<span th:text="${myListMapObj.key}"></span>
      <div th:each="myListMapObjList:${myListMapObj.value}">
        <span th:text="${myListMapObjList.id}"></span>
        <span th:text="${myListMapObjList.name}"></span>
        <span th:text="${myListMapObjList.phone}"></span>
        <span th:text="${myListMapObjList.address}"></span>
    	</div>
    </div>
  </div>
</body>
</html>

L、浏览器访问测试

循环遍历复杂集合

localhost:8090/property/each/all

C味

SpringBoot与Thymeleaf模板入门整合篇

11.4.15 条件判断 32)th:if 33)th:unless

    @RequestMapping(value = "/condition")
public String condition(HttpServletRequest request,Model model) {
    User user1 = null;
    model.addAttribute("user1",user1);
    
    User user2 = new User();
    user2.setId(1001);
    user2.setName("小岳岳");
    user2.setPhone("13900000000");
    user2.setAddress("北京市");
    model.addAttribute("user2",user2);
    
    model.addAttribute("sex",1);
    
    User user3 = new User();
    user3.setId(1002);
    user3.setName("孙悦");
    user3.setPhone("13200000000");
    user3.setAddress("北京市");
    model.addAttribute("user3",user3);
    
    request.getSession().setAttribute("user3",user3);
    return "condition";
}

condition.html 页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>条件判断</title>
</head>
<body>
  <h1>th:if 用法:如果满足条件显示,否则相反</h1>
  <div th:if="${sex eq 1}">
  	男:<input type="radio" name="sex" th:value="1"/>
  </div>
  <div th:if="${sex eq 0}">
  	女:<input type="radio" name="sex" th:value="0"/>
  </div>
  
  <h1>th:unless 用法:与 th:if 用法相反,即对条件判断条件取反</h1>
  <div th:unless="${sex == 1}">
  	男:<input type="radio" name="sex" th:value="1"/>
  </div>
  <div th:unless="${sex eq 0}">
  	女:<input type="radio" name="sex" th:value="0"/>
  </div>
  
  <div th:if="${user1 eq null}">
  	<h3 style="color: red">用户未登录</h3>
  </div>
  
  <div th:unless="${user2 == null}">
  	用户姓名:<span th:text="${user2.name}"></span>
  </div>
  
  <h1>从 session 中获取值</h1>
  <div th:if="${user3 != null}">
  	<span th:text="${user3.name}"></span>
  </div>
</body>
</html>

34)th:switch/th:case

switch,case 判断语句

    <h1>th:switch/th:case 用法</h1>
<div th:switch="${sex}">
  <span th:case="1">性别:男</span><br/>
  <span th:case="2">性别:女</span><br/>
  <span th:case="*">性别:保密</span>
</div>

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

35)浏览器访问测试

SpringBoot与Thymeleaf模板入门整合篇

11.4.16 th:inline

th:inline 有三个取值类型 (text, javascript 和 none),值为 none 什么都不做,没有效果

  • 内敛文本(th:inline=”text” )
  • 内敛文本表达式不依赖于 html 标签,直接使用 内敛表达式[[ 表达式]]即可获取动态数据,但必须要求在父级标签上加 th:inline = “text”属性

A、在 ThymeleafController  类中添加方法

    @RequestMapping(value = "/inline")
public String inlineText(Model model) {
    User user = new User();
    user.setId(1003);
    user.setName("杰克");
    user.setPhone("13899990000");
    user.setAddress("天津市");
    model.addAttribute("user",user);
    return "inline ";
}

B、创建 inline.html

    <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>内敛文本</title>
</head>
<body>
  <h1>标准变量表达式(展示数据)</h1>
  用户编号:<span th:text="${user.id}"></span><br/>
  用户姓名:<span th:text="${user.name}"></span><br/>
  用户手机号:<span th:text="${user.phone}"></span><br/>
  用户地址:<span th:text="${user.address}"></span><br/>
  <h1>内敛文本 th:inline="text"</h1>
  <div th:inline="text">
    用户编号:<div>[[${user.id}]]</div><br/>
    用户姓名:[[${user.name}]]<br/>
    用户手机号:[[${user.phone}]]<br/>
    用户地址:[[${user.address}]]<br/>
  </div>
</body>
</html>

C、浏览器访问测试

SpringBoot与Thymeleaf模板入门整合篇

注意:一般我们将 th:inline="text" 放到 标签中\

●内敛脚本(th:inline=”javascript” ) th:inline=”javascript” 在 js 代码中获取后台的动态数据 D、在 inline.html  页面上,添加如下代码

function showInlineJavaScript() {
  alert("欢迎 " + [[${user.name}]] + " 到我院指导工作!联系方式: " +
  	[[${user.phone}]]);
  }
</script>
<button th:onclick="showInlineJavaScript()">展示内容</button>
    

E、浏览器访问测试

SpringBoot与Thymeleaf模板入门整合篇

11.5 Thymeleaf字面量 字面量:对应数据类型的合法取值,可以在 html 页面直接使用,不需要后台传递

  1.  在 ThymeleafController 类中添加方法并准备数据

    @RequestMapping(value = "/literal")
public String literal(Model model) {
    model.addAttribute("success",true);
    model.addAttribute("flag",false);
    User user = new User();
    user.setId(1004);
    user.setName("贾玲");
    user.setPhone("13777777777");
    user.setAddress("北京市");
    model.addAttribute("user",user);
    return "literal";
}
  1.  创建 literal.html 页面

    <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Thymeleaf 字面量</title>
</head>
<body>
</body>
</html>
11.5.1 文本字面量\

用单引号'...'包围的字符串为文本字面量

    <h1>文本字面量:用单引号'...'包围的字符串</h1>
<a th:href="@{'/user/info?id=' + ${user.id}}">查看用户:文本字面的路径使用</a><br/>
<span th:text="您好"></span>

11.5.3 boolean字面量

    <h1>boolean 字面量</h1>
<div th:if="${success}">执行成功</div>
<div th:unless="${flag}">执行不成功</div>

11.5.4 null字面量

    <h1>null 字面量</h1>
<span th:if="${user ne null}">用户不为空</span><br/>
<span th:unless="${user eq null}">用户不为空(使用 th:unless 取反)</span><br/>

11.6 Thymeleaf字符串拼接

    <h1>文本字面量使用"+"拼接字符串</h1>
<span th:text="'共'+${totalRows}+'条'+${totalPage}+'页,当前第'+${currentPage}+'
页'"></span>
<h1>另一种更优雅的方式:使用"|要拼接的内容|"减少字符串拼接的加号</h1>
<span th:text="|共${totalRows}${totalPage}页,当前第${currentPage}页|"></span>

11.7 Thymeleaf  运算符

三元运算 :表达式?” 正确结果”:” 错误结果”

算术运算: :+ , - , * , / , %

关系比较: :> , < , >= , <= ( gt , lt , ge , le )

相等判断: :== , != ( eq , ne )

                       @RequestMapping(value = "/operator")
public String operator(Model model) {
    model.addAttribute("sex",1);
    return "operator";
}
 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>运算符</title>
</head>
<body>
  <h1>三元运算符</h1>
  <span th:text="${sex eq 1 ? '男':'女'}"></span><br/>
  <span th:text="${sex == 1 ? '男':'女'}"></span><br/>
  20*8=<span th:text="20 * 8"></span><br/>
  20/8=<span th:text="20 / 8"></span><br/>
  20+8=<span th:text="20 + 8"></span><br/>
  20-8=<span th:text="20 - 8"></span><br/>
  <div th:if="5 > 2">5>2 是真的</div>
  <div th:if="5 gt 2">5 gt 2 是真的</div>
</body>
</html>

运算符

C合

localhost:8090/property/operator

三元运算符

出邮

20*8-160

20/8-2.5

20+8-28

20-8-12

5-2是真的

5gt2是真的

SpringBoot与Thymeleaf模板入门整合篇

11.8 Thymaleaf表达式基本对象 模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由 #号开始引用,我们比较常用的内置对象 11.8.1 创建 SpringBoot项目并集成 thymeleaf 框架

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

SpringBoot与Thymeleaf模板入门整合篇

11.8.2 #request #request 相 当 于 httpServletRequest 对 象 , 这 是 3.x 版 本 , 若 是 2.x 版 本 使 用 #httpServletRequest,在页面获取应用的上下文根,一般在 js 中请求路径中加上可以避免 404

    <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Thymeleaf 表达式基本对象</title>
</head>
<body>
  <script type="text/javascript" th:inline="javascript">
    var basePath = [[${#httpServletRequest.getScheme() + "://" +
    #httpServletRequest.getServerName() + ":" +
    #httpServletRequest.getServerPort() +
    #httpServletRequest.getContextPath()}]];
    //http://localhost:8080/springboot/user/login
    //获取协议名称
    var scheme = [[${#request.getScheme()}]];
    //获取服务 IP 地址
    var serverName = [[${#request.getServerName()}]];
    //获取服务端口号
    var serverPort = [[${#request.getServerPort()}]];
    //获取上下文根
    var contextPath = [[${#request.getContextPath()}]];
    var allPath = scheme+"://"+serverName+":"+serverPort+contextPath;
    alert(allPath);
                    
    var requestURL = [[${#httpServletRequest.requestURL}]];
    var queryString = [[${#httpServletRequest.queryString}]];
    var requestAddress = requestURL + "?" +queryString;
    alert(requestAddress);
  </script>
</body>
</html>

11.8.3 #session

相当于 HttpSession 对象,这是 3.x 版本,若是 2.x 版本使用#httpSession

在后台方法中向 session 中放数据

    @Controller
public class UserController {

    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request,Model model,Integer id) {
        model.addAttribute("username","lisi");

        request.getSession().setAttribute("data","sessionData");

        return "index";
    }
}

从页面获取数据

    <h1>从SESSION中获取值</h1>
<span th:text="${#session.getAttribute('data')}"></span><br/>
<span th:text="${#httpSession.getAttribute('data')}"></span><br/>
<span th:text="${session.data}"></span><br/>

11.9 Thymeleaf表达式功能对象(了解)

模板引擎提供的一组功能性内置对象,可以在模板中直接使用这些对象提供的功能方法工作中常使用的数据类型,如集合,时间,数值,可以使用 Thymeleaf 的提供的功能性对象来处理它们;

内置功能对象前都需要加#号,内置对象一般都以 s 结尾

官方手册:www.thymeleaf.org/doc/tutoria…

#dates: java.util.Date 对象的实用方法:

#calendars: 和 dates 类似, 但是 java.util.Calendar 对象;

#numbers: 格式化数字对象的实用方法;

#strings: 字符串对象的实用方法: contains, startsWith, prepending/appending 等;

#objects: 对 objects 操作的实用方法;

#bools: 对布尔值求值的实用方法;

#arrays: 数组的实用方法;

#lists: list 的实用方法,比如

#sets: set 的实用方法;

#maps: map 的实用方法;

#aggregates: 对数组或集合创建聚合的实用方法;

    @Controller
public class UserController {

    @RequestMapping(value = "/function")
    public String function(Model model) {

        model.addAttribute("time",new Date());
        model.addAttribute("data","SpringBootHelloWorld");
        return "function";
    }
}
    <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <div th:text="${time}"></div>
  <div th:text="${#dates.format(time,'yyyy-MM-dd HH:mm:ss')}"></div>
  <div th:text="${data}"></div>
  <div th:text="${#strings.substring(data,0,10)}"></div>
  <div th:text="${#lists}"></div>
</body>
</html>

青山不改,绿水常流。谢谢大家!

转载自:https://juejin.cn/post/7141649607322238984
评论
请登录