Thymeleaf——学习笔记

参考/摘录书籍:自己整理、Spring Boot的Web开发 著○疯狂软件
参考图片:来自网络/自己提供
说明:本人相关博客仅供学习参考!

一、介绍

1.0 概述

  模板引擎的原理:在html页面上为动态数据保留占位符${xxx},模板引擎负责解析xxx,从服务器端找到名为xxx的数据,并将动态数据代替${xxx}。
Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个吸引人的特点:
  1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  3. Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

1.1 引入 Thymeleaf

首先要想如下所示改写 html 标签。这样才可以在其它标签里面使用th:*这样的语法。

<html xmlns:th="http://www.thymeleaf.org">

通过xmlns:th="http://www.thymeleaf.org"命名空间,引入Thymeleaf模板引擎,将静态页面转换为动态页面。需要进行动态处理的元素都要使用th:为前缀。

1.2 引入 URL

Thymeleaf对于URL的处理是通过语法@{···}来处理的。

<link rel="stylesheet" th:href="@{/css/public.css}"/>

<script th:src="@{/js/time.js}"></script>

<a th:href="@{http://www.baidu.com/a.png}">绝对路径</a>
<a th:href="@{/}">相对路径【在Spring MVC项目中也相当于项目的根路径】</a>
<a th:href="@{/css/jquery.css}">访问项目根路径下static文件夹下的css文件夹下的资源路径</a>

1.3 表达式

1.4 字符串操作

1.5 运算符

1.6 条件判断

1.7 循环

1.8 内置对象

1.9 内联JS

//【HTML 代码】
<a href="javascript:;" id="toLogout" >退出</a>

//【JavaScript 代码】
<!-- 注意:javaScript脚本需要使用th:inline内联,否则不能获取项目路径 -->
<script th:inline="javascript">
    var conf = document.getElementById("toLogout");
    conf.onclick = function (){
        //获取网站的前缀
        var ctx = /*[[@{/}]]*/''; //也可以不加两个单引号【不加的话会爆红但是不影响获取】
        console.log(ctx)
        // var ctx = [[${#httpServletRequest.getContextPath()}]];
        if (confirm("确认退出?")){
            //window.location.href : 跳转
            //window.location.replace : 方法可用一个新文档取代当前文档。
            window.location.href="/admin/logout";
        }
    };
</script>

二、使用

2.1 Spring MVC 和 Thymeleaf 整合

2.1.1 引入依赖(Spring MVC)

<!-- Spring5和Thymeleaf整合包 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.12.RELEASE</version>
</dependency>

2.1.2 配置thymeleaf的视图解析器

<!--配置thymeleaf的视图解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <property name="order" value="1"/>
    <property name="characterEncoding" value="UTF-8"/>
    <!-- 模板引擎 -->
    <property name="templateEngine">
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
        	<!-- 模板解析器 -->
            <property name="templateResolver">
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                    <!-- 视图前缀 -->
                    <property name="prefix" value="/WEB-INF/templates/"/>
                    <!-- 视图后缀 -->
                    <property name="suffix" value=".html"/>
                    <property name="templateMode" value="HTML5"/>
                    <property name="characterEncoding" value="UTF-8" />
                </bean>
            </property>
        </bean>
    </property>
</bean>

2.2 Spring Boot 和 Thymeleaf 整合

  Thymeleaf 包下最重要的类是 ThymeleafAutoConfiguration 和 ThymeleafProperties 。
  ThymeleafAutoConfiguration 类对继承所需要的 Bean 进行自动配置,包括templateEngine 和 templateResolver 的配置。
  ThymeleafProperties 类读取 application.prpperties 配置文件,设置 Thymeleaf 的属性以及默认配置。

2.2.1 application.yml 配置文件

# 配置thymeleaf
spring:
  thymeleaf:
    cache: false # 关闭thymeleaf的模板缓存【开发时关闭缓存,不然没办法实时看到页面】,默认开启
    encoding: UTF-8 # 模板的编码设置,默认为UTF-8
    prefix: classpath:/templates/ # 设置前缀,默认放在 classpath:/templates/ 目录下
    mode: HTML5 # 要应用于模板的模板模式,默认为 HTML
    servlet:
      content-type: text/html  # 写入 HTTP 响应的 Content-Type 值。默认为 text/html   

2.2.2 pom.xml 文件添加 thymeleaf 依赖

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

x、应用案例

x.1 变量表达式

  变量表达式OGNL表达式Spring EL表达式(在Spring术语中也叫model attributes)。例如:

<!-- 文本替换【下列两个写法等价】 -->
<span th:text="${session.loginUser.username}">张三</span>
<span>[[${session.loginUser.username}]]</span>
<!-- 属性赋值/遍历 -->
<li th:each="user : ${userList}">  
···

【说明】

  1. Thymeleaf不适用 OGNL ,而是 SpringEL 实现变量表达式,因此所有的${}*{}表达式将用Spring的表达式引擎进行处理。

x.1.1 单选按钮(th:field)

<div class="form-group">
	<label for="inputPassword3" class="col-sm-2 control-label">性别</label>
	<div class="col-sm-10">
		<label class="checkbox-inline">
			<input type="radio" name="sex" value="" id="sex1" th:field="${student.sex}"></label>
		<label class="checkbox-inline">
			<input type="radio" name="sex" value="" id="sex2" th:field="${student.sex}"></label>
	</div>
</div>

x.1.2 下拉选项(th:each、th:value、th:text)

情景一

<!-- 下拉列表显示【th:each遍历${collegeList集合};th:value给该选项提供值;th:text显示该下拉选项所表示的值】 -->
<select class="form-control" name="collegeId">
	<option th:each="item:${collegeList}" th:value="${item.collegeId}" th:text="${item.collegeName}"></option>
</select>

情景二

<!-- 在处理下拉列表回显时自动选中,要求条件:“值1”=“值2”【th:field="值1",th:value="值2"】 -->
<select class="form-control" name="teacherId" id="teacherid">
	<option th:each="t:${teacherList}" th:value="${t.userId}" th:text="${t.userName}" th:field="${course.teacherId}"></option>
</select>

情景三

<!-- 当th:field中的值和前面的value中的值相等时该选项被选中 -->
<select class="form-control" name="courseType" id="coursetype">
	<option value="必修课" th:field="${course.courseType}">必修课</option>
	<option value="选修课" th:field="${course.courseType}">选修课</option>
	<option value="公共课" th:field="${course.courseType}">公共课</option>
</select>

x.2 URL 相关

<!-- 静态资源要用单引号引起来 -->
<a th:href="@{'/bookOperation/toUpdateView/'+${b.bid}}">修改</a>

<a onclick="deleteBook()" th:href="@{'/bookOperation/bookDelete/'+${b.bid}}">删除</a>

<!-- 新建一个表单,用于把POST转为DELETE请求 -->
<form id="postToDelete" action="" method="post">
    <!-- 将post请求转换为指定的请求方法DELETE,借助HiddenHttpMethodFilter 过滤器把post请求自动转换为DELETE请求【注意规范】 -->
    <input type="hidden" name="_method" value="DELETE" />
</form>

<script>
    //处理删除操作
    function deleteBook(){
        var flag = confirm("是否删除该图书?");
        if (flag){
            //event.preventDefault()是通知浏览器不要执行与事件关联的默认动作【这里取消默认超链接跳转动作】
            event.preventDefault();
            var postToDelete = document.getElementById('postToDelete');
            //获取到删除按钮超链接中的跳转路径,并将其赋给postToDelete表单的action属性
            postToDelete.action = event.target.href;
            //表单提交
            postToDelete.submit();
        }
    }
</script>

x.3 form表单提交(th:action)

<form class="form-horizontal" role="form" th:action="@{/admin/updateCourse}" id="searchForm" method="post">
	<!-- 把PSOT请求转换为PUT请求【适应RESTFUL风格】(post和get请求不用写这句代码) -->
	<input type="hidden" name="_method" value="PUT">
	<!-- 隐藏域存放页号 -->
	<input type="hidden" name="pageNum" id="currentPage" value="1">
	<!-- 回显搜索的关键字 -->
	<input type="text" class="form-control" placeholder="请输入姓名"
						id="keyword" name="userName"
						th:value="${studentQueryVo.userName}"/>
	<span class="input-group-addon btn" id="sub" onclick="fetchData(1)">搜索</span>
</form>

<script>
	//提交表单,分页显示数据列表
	function fetchData(num) {
	    $('#currentPage').val(num);
	    $('#searchForm').submit();
	}
</script>

x.4 动态传参

(情景1)分页条传参

<!-- 【一】GET风格传参 -->
<!-- thymeleaf发送GET请求参数时,要用(参数名1=value1,参数名2=value2,...)来表示;-->
<a th:href="@{/emp/list(pageNum=${num},pageSize=${size})}" th:text="${num}" />
<!-- 上面代码解析后等价于:/emp/list?pageNum=1&pageSize=3 -->

<!-- 【二】REST风格传参 -->
<a th:href="@{'/user/list/'+${n}+'/4'}" th:text="${n}"></a>
<!--【上面这个例子是发送分页参数】-->

【注意】

  1. 拼接地址参数的时候,静态地址用单引号“'静态参数'”引起来,再用加号“+”拼接动态参数;

x.5 运算符

x.5.1 性别辨别

<!--【写法1】 -->
<td th:text="${emp.gender==0?'':''}"></td>

<!--【写法2】 -->
<td th:text="${emp.gender}==0?'':''"></td>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值