SpringBoot集成Thymeleaf模板

二.集成Thymeleaf模板

2.1 了解

  • 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 的官方网站:http://www.thymeleaf.org
    Thymeleaf 官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

2.2 SpringBoot集成Thymeleaf

1.创建Springboot项目,添加web和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>

2.application.properties中对Thymeleaf进行配置
thymeleaf是一个模板引擎,缓存的意思是加载一次模板之后便不会在加载了,对于生产环境应该加上缓存,但是在开发过程中如果打开缓存,不方便开发人员调试。试想一下,改一行html,就需要重启服务器,肯定是不方便的
在这里补充一下:本地开发环境下,需要把缓存关闭,否则调试成本太大。其他环境下缓存都需要打开。

#设置thymeleaf模版引擎的缓存,设置为false关闭,默认为true开启
spring.thymeleaf.cache=false

#设置thymeleaf模版引擎的前/后缀,(可选项),视图解析,默认就是resources/templates
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

3.创建ThymeleafController去映射到模板页面(和SpringMVC基本一致)

@Controller
public class IndexController {
    @RequestMapping(value = "/index")
    public String index(Model model) {
        model.addAttribute("data","SpringBoot Thymeleaf");
        return "index"; //之前的视图解这里路径会变为/templates/index.html
    }
    @RequestMapping(value = "/index1")
    public ModelAndView index1() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        mv.addObject("data","SpringBoot");
        return mv;
    }
}

4.在src/main/resources的templates下创建一个index.html页面
HTML页面恶< html >元素中加入以下属性:

<html xmlns:th="http://www.thymeleaf.org">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot集成Thymeleaf</title>
</head>
<body>
<div th:text="${data}">xxx</div>
<h1>Thymeleaf</h1>
<h1>Thymeleaf</h1>
<h1>Thymeleaf</h1>
</body>
</html>

5.启动程序,浏览访问http://localhost:8080/index
在这里插入图片描述
注意:Springboot使用thymeleaf作为视图展示,约定将模板文件放置在src/main/resource/templates目录下,静态资源放置在src/main/resource/static目录下

2.3 Thymeleaf的表达式

2.3.1初始化步骤

1.创建SpringBoot的web项目并使用模板引擎
如上例
2.在application.properties中设置thymeleaf参数

#设置thymeleaf模版引擎的缓存,设置为false关闭,默认为true开启
spring.thymeleaf.cache=false

#设置thymeleaf模版引擎的前/后缀,(可选项),当前配置的路径其实默认就是。
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

3.创建实体User实体类

public class User {
    private Integer id;
    private String username;
    private Integer age;
}

4.创建ThymeleafController类

5.在src/main/resources/templates在创建html页面

2.3.2 表达式

1.标准变量表达式
标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和EL中的 $ {} 相
同。Thymeleaf 中的变量表达式使用${变量名} 的方式获取Controller中model其中的数据

<body>
<h1>标准变量表达式:${} -> (推荐)</h1>
用户编号:<span th:text="${user.id}"></span><br/>
用户姓名:<span th:text="${user.username}"></span><br/>
用户年龄:<span th:text="${user.age}"></span><br/>

2.选择变量表达式

<h1>选择变量表达式(星号表达式):*{} -> (不推荐)</h1>
<!--
    *{}必须使用th:object属性来绑定这个对象
    在div子标签中使用*来代替绑定的对象${user}
-->
<div th:object="${user}">
    用户编号:<span th:text="*{id}"></span><br/>
    用户姓名:<span th:text="*{username}"></span><br/>
    用户年龄:<span th:text="*{age}"></span><br/>
</div>
<h1>标准变量表达式与选择变量表达式的混合使用(不推荐)</h1>
用户编号<span th:text="*{user.id}"></span><br/>
用户年龄<span th:text="*{user.age}"></span><br/>
用户姓名<span th:text="*{user.username}"></span><br/>

3.URL表达式
主要用于链接、地址的展示,可用于
< script src="…">、< link href="…">、< a href="…">、< form action="…">、< img src="">等,可以在URL路径中动态获取数据

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>URL路径表达式</title>
</head>
<body>
<h1>URL路径表达式:@{....}</h1>
<h2>a标签中的绝对路径(没有参数)</h2>
<a href="http://www.baidu.com">传统写法:跳转至百度</a><br/>
<a th:href="@{http://www.tx.com}">路径表达式:路径到</a><br/>
<a th:href="@{http://localhost:8080/user/detail1}">跳转至:/user/detail1</a><br/>
<a href="http://localhost:8080/user/detail1">传统写法跳转至:/user/detail1</a><br/>

<h2>URL路径表达式,相对路径[没有参数](实际开发中推荐使用的)</h2>
<a th:href="@{/user/detail1}">跳转至:/user/detail1</a><br/>

<h2>绝对路径(带参数)(不推荐使用)</h2>
<a href="http://localhost:8080/test?username='zhangsan'">绝对路径,带参数:/test,并带参数username</a><br/>
<a th:href="@{http://localhost:8080/test?username=zhangsan}">路径表达工写法,带参数:/test,并带参数username</a><br/>

<h2>相对路径(带参数)</h2>
<a th:href="@{/test?username=lisi}">相对路径,带参数</a>

<h2>相对路径(带参数:后台获取的参数值)</h2>
<!--/test?username=1001-->
<a th:href="@{'/test?username='+${id}}">相对路径:获取后台参数值</a>

<h2>相对路径(带多个参数:后台获取的参数值)</h2>
<!--
    /test1?id=1001&username=zhaoliu&age=28
-->
<a th:href="@{'/test1?id='+${id}+'&username='+${username}+'&age='+${age}}">相对路径(带多个参数:后台获取的参数值)</a>
<a th:href="@{/test1(id=${id},username=${username},age=${age})}">强烈推荐使用:@{}相对路径(带多个参数:后台获取的参数值)</a><br/>
<a th:href="@{'/test2/'+${id}}">请求路径为RESTful风格</a><br/>
<a th:href="@{'/test3/'+${id}+'/'+${username}}">请求路径为RESTful风格</a><br/>
</body>
</html>

2.4 Thymeleaf的常见属性

大部分属性和html的一样,只不过前面加了一个th前缀
1.创建SpringBoot的web项目并使用模板引擎
2.application.properties 设置thymeleaf参数

#设置端口号
server.port=8080
#设置上下文根
server.servlet.context-path=/property
#thymeleaf缓存默认开启,开发阶段关闭
spring.thymeleaf.cache=false
#设置thymeleaf前缀
spring.thymeleaf.prefix=classpath:/templates/
#设置thymeleaf后缀
spring.thymeleaf.suffix=.html

3.创建实体类
4.创建ThymeleafController类
5.创建index页面

th:action

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

<form th:action="@{'/user/login?id='+${user.id}}"></form>
<h2>以下两种方式获取不到用户 id</h2>
<form action="'/user/login?id='+${user.id}"></form>
<form action="/user/login"+${user.id}></form>

用户年龄数据无法解析
因为我们Thymeleaf是以html为载体的,所以html不会认识${}语法。
我们请求的流程是,发送请求给服务器,服务器接收请求后,处理请求,跳转到指定的静态html页面,在服务器端,Thymeleaf模板引擎会按照它的语法,对动态数据进行处理,所以如果要是th开头,模板引擎能够识别,会在服务器端进行处理,获取数据;如果没有以th开头,那么Thymeleaf模板引擎不会处理,直接返回给客户端了。

th:method

<form th:method="post" th:action="@{/test1}">
    用户编号:<input type="text" id="id" th:name="id" /><br/>
    用户姓名:<input type="text" th:id="username" th:name="username" /><br/>
    用户年龄<input type="text" th:id="age" th:name="age" /><br/>
    <input type="submit" value="submit"/>
</form>

th:href

<a href="http://www.baidu.com">超链接百度</a><br/>
<a th:href="'http://www.baidu.com?id=' + ${user.id}">th:href 链接</a>

th:src

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

<h1>th:src 属性的使用</h1>
<!--以下方式无法引入 js-->
<script src="/static/js/jquery-1.7.2.min.js"></script>
<!--该方法是常用方法-->
<script type="text/javascript" th:src="@{/jquery-1.7.2.min.js}"></script>
<script>
	 $(function () {
	 	alert("引入 js 文件");
 });
</script>

这种方式比传统方式的好处是,在 URL 表达式前加/,会自动加上上下文根,避免 404 找不到资源的情况。

th:id

类似 html 标签中的 id 属性

<span th:id="${hello}">aaa</span>

th:name

设置名称

<input th:type="text" th:id="userName" th:name="userName">

th:value

类似 html 标签中的 value 属性,能对某元素的 value 属性进行赋值

<input type="hidden" id="userId" name="userId" th:value="${userId}">

th:attr

该属性也是用于给 HTML 中某元素的某属性赋值,好处是可以给 html 中没有定义的属性动态的赋值

<h1>th:attr 属性的使用</h1>
<span zhangsan="${user.name}"></span>
<!--通过 th:attr 对自定义的属性赋值-->
<span th:attr="zhangsan=${user.name}"></span>

th:text

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

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

th:object

用于数据对象绑定
通常用于选择变量表达式(星号表达式)

th:onclick

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

th:style

设置样式

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

*th:each(常用)

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

<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>
  • interStat 是循环体的信息,通过该变量可以获取如下信息
    index: 当前迭代对象的 index(从 0 开始计算)
    count: 当前迭代对象的个数(从 1 开始计算)这两个用的较多
    size: 被迭代对象的大小
    current: 当前迭代变量
    even/odd: 布尔值,当前循环是否是偶数/奇数(从 0 开始计算)
    first: 布尔值,当前循环是否是第一个
    last: 布尔值,当前循环是否是最后一个
    注意:循环体信息 interStat 也可以不定义,则默认采用迭代变量加上 Stat 后缀,即 userStat
<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>
<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>
<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>

th:if

th:unless

<head>
    <meta charset="UTF-8">
    <title>条件判断</title>
</head>
<body>
<h1>th:if 用法:如果满足条件显示(执行),否则相反</h1>
<div th:if="${sex eq 1}"></div>
<div th:if="${sex eq 0}"></div>
<h1>th:unless 用法:与th:if用法相反,即条件判断取反</h1>
<div th:unless="${sex ne 1}"></div>

th:switch/th:case

<h1>th:switch/th:case用法</h1>
<div th:switch="${productType}">
    <span th:case="0">产品0</span>
    <span th:case="1">产品1</span>
    <span th:case="*">无此产品</span>
</div>

th:inline

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

2.5Thymeleaf字面量

字面量与变量常量区分

<head>
    <meta charset="UTF-8">
    <title>字面量</title>
</head>
<body>
<h1>文本字面量,用单引号'....'的字符串就是字面量</h1>
<a th:href="@{'/user/detail?sex=' + ${sex}}">查看性别</a>
<span th:text="Hello"></span>

<h1>数字字面量</h1>
今年是<span th:text="2020">1949</span><br/>
20年后是<span th:text="2020+20">1969</span><br/>

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

<h1>null字面量</h1>
<span th:text="${user.id}"></span>
<div th:unless="${userDetail eq null}">
    对象已创建,地址不为空
</div>

<div th:if="${userDetail.id eq null}"></div>

2.6 字符串拼接

<head>
    <meta charset="UTF-8">
    <title>字符串拼接</title>
</head>
<body>
	<span th:text="''+${totalRows}+''+${totalPage}+'页,当前第'+${currentPage}+'页,首页 上一页 下一页 尾页'">共120条12页,当前第1页,首页 上一页 下一页 尾页</span>
	
	<h1>使用更优雅的方式来拼接字符串: |要拼接的字符串内容|</h1>
	
	<span th:text="|共${totalRows}条${totalPage}页,当前第${currentPage}页,首页 上一页 下一页 尾页|">共120条12页,当前第1页,首页 上一页 下一页 尾页</span>
</body>

2.7Thymeleaf 运算符

三元运算:表达式?”正确结果”:”错误结果”
算术运算:+ , - , * , / , %
关系比较::> , < , >= , <= ( gt , lt , ge , le )
相等判断:== , != ( eq , ne)

2.8 Thymeleaf表达式基本对象

模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由#号开始引用,我们比较常用的内置对象

<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/>

<script type="text/javascript" th:inline="javascript">
    // http://localhost:8080/springboot/user/detail
    //获取协议名称
    var scheme = [[${#request.getScheme()}]];

    //获取服务器名称
    var serverName = [[${#request.getServerName()}]];

    //获取服务器端口号
    var serverPort = [[${#request.getServerPort()}]];

    //获取上下文根
    var contextPath = [[${#request.getContextPath()}]];

    var allPath = scheme + "://" +serverName+":"+serverPort+contextPath;

    var requestURL = [[${#httpServletRequest.requestURL}]];
    var queryString = [[${#httpServletRequest.queryString}]];

    var requestAddress = requestURL + "?" +queryString;

    alert(requestAddress);

</script>
</body>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值