Thymeleaf学习

一、 Thymeleaf基本使用

1.1 什么时候需要

适用前后端不分离的单体项目;

不适合前后端分离(后端只需要提高接口返回数据;)

1.2 简介

Thymeleaf 的主要目标是将优雅的自然模板带到开发工作流程中,并将 HTML 在浏览器
中正确显示,并且可以作为静态原型,让开发团队能更容易地协作。Thymeleaf 能够处理
HTML,XML,JavaScript,CSS 甚至纯文本。

简单说:一个模板引擎,为html做数据渲染
一个html页面需要的某些数据,可以通过thymeleaf一些标记来替换掉,代表该数据是来源于服务端, 化解了 html 与 jsp 无法交互的问题;

1.3 Springboot整合 Thymeleaf

<!--添加 Thymeleaf 启动器依赖--> 
<dependency> 
	<groupId>org.springframework.boot</groupId> 
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

补充知识:
因为 resources目录下的 templates 安全性是比较高的,它不允许我们直接通过uri(localhost:8080.index.html)来访问。
我们就需要通过 Controller层,传递数据给 templates来完成数据的渲染;
在这里插入图片描述

Controller

/*** 页面跳转 Controller */
 @Controller
public class PageController {/*** 页面跳转方法 */ 
	@GetMapping("/show") 
	public String showPage(Model model){
 		model.addAttribute("msg","Hello Thymeleaf");
 		return "index"; 
 		}
 	}

视图 Html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd"> 
<html xmlns:th="http://www.thymeleaf.org"> 
<head> 
	<title>Thymeleaf首页</title>
</head> 
<body> 
	<span th:text="Thymeleaf学习"></span>
 	<hr/> 
 	<span th:text="${msg}">
 </span> 
 </body> 
 </html>

二、 Thymeleaf 各种数据类型的操作

2.1 字符串与变量输出操作

2.1.1、 th:text

th:text
在页面中输出值

2.1.2、 th:value

th:value
可以将一个值放入到 input 标签的 value 中

2.2 字符串操作

Thymeleaf 提供了一些内置对象,内置对象可直接在模板中使用。
这些对象是以#引用 的

2.2.1 使用内置对象的语法
  1. 引用内置对象需要使用
  2. 大部分内置对象的名称都以 s 结尾。如:strings、numbers、dates
  • ${#strings.isEmpty(key)}
    判断字符串是否为空,如果为空返回 true,否则返回 false

  • ${#strings.contains(msg,‘T’)}
    判断字符串是否包含指定的子串,如果包含返回 true,否则返回 false

  • ${#strings.startsWith(msg,‘a’)}
    判断当前字符串是否以子串开头,如果是返回 true,否则返回 false

  • ${#strings.endsWith(msg,‘a’)}
    判断当前字符串是否以子串结尾,如果是返回 true,否则返回 false

  • ${#strings.length(msg)}
    返回字符串的长度

  • ${#strings.indexOf(msg,‘h’)}
    查找子串的位置,并返回该子串的下标,如果没找到则返回-1

  • ${#strings.substring(msg,2)} ; ${#strings.substring(msg,2,5)}
    截取子串,用户与 jdk String 类下 SubString 方法相同

  • ${#strings.toUpperCase(msg)} ; ${#strings.toLowerCase(msg)}
    字符串转大小写。

2.3 日期格式化处理

  • ${#dates.format(key)}
    格式化日期,默认的以浏览器默认语言为格式化标准

  • ${#dates.format(key,‘yyyy/MM/dd’)}
    按照自定义的格式做日期转换

  • ${#dates.year(key)} ${#dates.month(key)} ${#dates.day(key)}
    Year:取年 Month:取月 Day:取日

2.4 条件判断

  • th:if
    条件判断

  • th:switch / th:case
    th:switch / th:case 与 Java 中的 switch 语句等效,有条件地显示匹配的内容。如果有 多个匹配结果只选择第一个显示。 th:case=““表示 Java 中 switch 的 default,即没有 case 的值为 true 时则显示 th:case=”” 的内容。

2.5 迭代遍历

  • th:each
    迭代器,用于循环迭代集合

  • th:each 状态变量

  1. index:当前迭代器的索引 从 0 开始
  2. count:当前迭代对象的计数 从 1 开始
  3. size:被迭代对象的长度
  4. odd/even:布尔值,当前循环是否是偶数/奇数 从 0 开始
  5. first:布尔值,当前循环的是否是第一条,如果是返回 true 否则返回 false
  6. last:布尔值,当前循环的是否是最后一条,如果是则返回 true 否则返回 false

3.6 th:each 迭代 Map

<table border="1" width="50%"> 
	<tr>
		<th>ID</th>
		<th>Name</th> 
		<th>Age</th> 
		<th>Key</th> 
	</tr> 
	<tr th:each="m : ${map}"> 
		<td th:text="${m.value.id}"></td> 
		<td th:text="${m.value.name}"></td> 
		<td th:text="${m.value.age}"></td> 
		<td th:text="${m.key}"></td> 
	</tr> 
</table>

2.7 操作域对象

  • HttpServletRequest
request.setAttribute("req", "HttpServletRequest");
<span th:text="${#httpServletRequest.getAttribute('req')}"></span> 
<span th:text="${#request.getAttribute('req')}"></span>
  • HttpSession
request.getSession().setAttribute("sess", "HttpSession"); 
<span th:text="${session.ses}"></span><br/> 
<span th:text="${#session.getAttribute('ses')}"></span>
<br/>

ServletContext

request.getSession().getServletContext().setAttribute("app", "Application"); 
<span th:text="${application.app}"></span> 
<span th:text="${#servletContext.getAttribute('app')}"></span>

2.8 URL 表达式

  1. 语法
    在 Thymeleaf 中 URL 表达式的语法格式为@{}
  2. URL 类型
  • 绝对路径
<a th:href="@{http://www.baidu.com}">绝对路径</a>
  • 相对路径

相对于当前项目的根

<a th:href="@{/show}">相对路径</a>

相对于服务器路径的根

<a th:href="@{~/project2/resourcename}">相对于服务器的根</a>
  1. 在 URL 中传递参数

在普通格式的 URL 中传递参数

<a th:href="@{/show?id=1&name=zhangsan}">普通 URL 格式传参</a> 
<a th:href="@{/show(id=1,name=zhangsan)}">普通 URL 格式传参</a> 
<a th:href="@{'/show?id='+${id}+'&name='+${name}}"> 普 通 URL 格 式 传 参 </a>
<a th:href="@{/show(id=${id},name=${name})}">普通 URL 格式传参</a>

在 restful 格式的 URL 中传递参数

<a th:href="@{/show/{id}(id=1)}">restful 格式传参</a> 
<a th:href="@{/show/{id}/{name}(id=1,name=admin)}">restful 格式传参</a> 
<a th:href="@{/show/{id}(id=1,name=admin)}"> restful 格式传参 </a>
<a th:href="@{/show/{id}(id=${id},name=${name})}">restful 格式传参</a>

三、在配置文件中配置 Thymeleaf

常用配置

spring.thymeleaf.prefix=classpath:/templates/suibian/ 
#配置视图模板类型,如果视图模板使用的 是 html5 需要配置
spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML 
spring.thymeleaf.encoding=utf-8 
spring.thymeleaf.servlet.content-type=text/html #响应类型 
#配置页面缓存 
spring.thymeleaf.cache=false

测试代码:

Controller

@Controller
public class ThymeleafController {

    @GetMapping("/show")
    public String test(Model model, HttpServletRequest request){
        model.addAttribute("msg","hello Thymeleaf!");
        model.addAttribute("str","String.test;");
        model.addAttribute("date", new Date());
        model.addAttribute("age",35);
        List <User> list = new <User> ArrayList();
        list.add(new User("小红",20,"女"));
        list.add(new User("小名",31,"男"));
        list.add(new User("小布",12,"女"));
        model.addAttribute("list",list);
        Map<String,User> map = new HashMap();
        map.put("user1",new User("小红",20,"女"));
        map.put("user2",new User("xiaoming",31,"男"));
        map.put("user3",new User("小布",12,"女"));
        model.addAttribute("map",map);

        request.setAttribute("req","HttpServletRequest");
        request.getSession().setAttribute("ses","HttpSession");
        request.getServletContext().setAttribute("app","application");
        return "index";
    }

    @GetMapping("/show2")
    public String test2(){
        return "index2";
    }

    @GetMapping("/show3/{name}")
    public String test3(String id ,String name){
        return "index2";
    }
}

index 页面

index1
<!DOCTYPE html >
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- test1 -->
    <title>ThymeleafStudy</title></head>
<body>
<!--2.1.1、 th:text -->
  <span th:text="helloThymeleaf"></span>
  <hr/>
  <span th:text="${msg}">
    </span>
  <hr/>
<!--2.1.2、 th:value -->
    <input type="button" th:value="${msg}">
  <hr/>
<!-- ${#strings.isEmpty(key)} -->
  <span th:text="${#strings.isEmpty(str)}">
    </span>
<hr/>
<!-- ${#strings.substring(str,2)} -->
  <span th:text="${#strings.substring(str,2)}"/>
<hr/>
<!-- 未转化前:-->
  <span th:text="${date}"/>
<hr/>
<!--  ${#dates.format(key)} 默认的以浏览器默认语言为格式化标准 -->
  <span th:text="${#dates.format(date)}"/>
<hr/>
<div>
  <span th:if="${age} >'30'" >
     you are old;
  </span>
</div>

<hr/>
<table border="1" with="50%">
       <tr>
         <th>Name</th>
         <th>Age</th>
         <th>Sex</th>
       </tr>
    <tr th:each="u: ${list}" >
      <td th:text="${u.name}"></td>
      <td th:text="${u.age}"></td>
      <td th:text="${u.sex}"></td>
</tr>
</table>
<hr/>

<table border="1" with="50%">
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Sex</th>
        <th>Key</th>
    </tr>
    <tr th:each="m : ${map}" >
        <td th:text="${m.value.name}"></td>
        <td th:text="${m.value.age}"></td>
        <td th:text="${m.value.sex}"></td>
        <td th:text="${m.key}"></td>
    </tr>
</table>
<hr/>

<!--操作 域对象 -->
<hr/>
HttpServletRequest  <span th:text="${#httpServletRequest.getAttribute('req')}"></span>
                    <span th:text="${#request.getAttribute('req')}"></span>
<hr/>
HttpSession  <span th:text="${session.ses}"></span>
            <span th:text="${#session.getAttribute('ses')}"></span>
<hr/>
ServletContext <span th:text="${application.app}"></span>
                <span th:text="${#servletContext.getAttribute('app')}"></span>
<hr/>
<!--URL 表达式-->
    <a th:href="@{http://www.baidu.com}">绝对路径</a>
<hr/>
<!-- 跳转都 controller(show2) --》 再跳转到 index2页面 -->
    <a th:href="@{/show2}">相对路径</a>
<hr/>
<a th:href="@{~/show2}">相对于服务器的根</a>
<hr/>
<!--在 URL 中传递参数-->
    <a th:href="@{/show3(id=${1},name=${ww})}">普通 URL 格式传参</a>
<hr/>

<!--在 restful 格式的 URL 中传递参数-->
<a th:href="@{/show3/{id}(id=${1},name=${hh})}">restful 格式传参</a>
<hr/>
</body>
</html>

index2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>跳转后的页面 =2=</title>
</head>
<body>
<span th:text="跳转后的页面 "></span>
</body>
</html>

pojo

package com.cc.springbootthymeleaf.pojo;

/**
 * Description
 * Create by salvatore
 * Date 2023/10/14 23:03
 */
public class User {
    private String name;
    private Integer age;
    private String sex;

    public User() {
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

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

学习:https://www.bilibili.com/video/BV1WH4y1S7EV?p=40&vd_source=4753af08dc12ba29bcc0b79e921e5dd4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值