SpringBoot系列(二)

SpringBoot 的 web 开发

SpringBoot 项目中引入 thymeleaf
为什么要在 SpringBoot 项目中引入 thymeleaf(模板引擎)

在业内已经有多重动态页面模板引擎的情况下,SpringBoot 官方推荐一个性能并不占优 势的 thymeleaf,可能主要是政治原因,重复发明轮子。常用的模板引擎有:Beetl、JSP、 Freemarker、Thymeleaf、Velocity。其中公认性能最优异的是 Beetl,其次可能是 JSP。

在这里插入图片描述
在这里插入图片描述

但是,作为官方推荐的模板引擎,还是要有一定的了解。随着以后 thymeleaf 性能的改进, 也许会更加受欢迎。

模板引擎

常用的模板引擎有:JSP、Freemarker、Thymeleaf、Velocity。模板引擎的工作原理如下。
[外链图片转存失败(img-TG3RvKqA-1568009825461)(/images/pasted-20.png)]

使用Thymeleaf

使用模板之前,首先需要引入依赖包:

<!--START 引入 thymeleaf 的依赖 START--> 
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-thymeleaf</artifactId> 
</dependency> 
<!--END 引入 thymeleaf 的依赖 END-->

注意:默认引入 thymeleaf 的版本是 2.1.6,但是这个版本有一点低,那么如果提高 thymeleaf 的版本呢?我们可以在 pom.xml 中的 properties 节点里面添加如下代码。

<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3 主程序 layout2 以上版本 --> 
<!-- thymeleaf2 layout1--> 
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
Thymeleaf的视图解析器

我们在项目中搜索ThymeleafProperties类。
在这里插入图片描述
我们可以看到,ThymeleafProperties指定了html为视图解析器。
如上图所示,只要把 HTML 页面放在 classpath:/templates/下,thymeleaf 就能自动渲染。我们可以来测试一下ThymeleafProperties

1.在控制器类添加一段访问代码
在这里插入图片描述
2.在resource目录下创建一个templates目录(如若有则不用创建),新建一个success.html页面
在这里插入图片描述
3.启动项目测试
在这里插入图片描述

Thymeleaf使用&语法

1)导入命名空间

<html lang=“en” xmlns:th=“http://www.thymeleaf.org”>

2)使用 thymeleaf 的语法,在页面上面输出在 Controller 中保存到作用域中的值。

第一种方式取值:<p th:text=" n a m e &quot; &gt; &lt; / p &gt; 第 二 种 方 式 取 值 : [ [ {name}&quot;&gt;&lt;/p&gt; 第二种方式取值:[[ name"></p>[[{name}]]

两种方式看什么场合来决定使用那种取值语法。

3)常用th标签

标签说明
th:insert
th:replace
Html 代码片段包含,类似于 jsp:include
th:each遍历,类似于 c:forEach
th:case
th:object
th:with
声明变量,类似于 c:set
th:value
th:href
th:src
修改指定的属性默认值,如th:href修改 a标签中的 href属性。ht:src 修改 script 中的 src 属性。
th:text
th:utext
修改标签体的内容,th:text 是会进行转义字符串,如 <th:text=”${name}”/>如果取出的值中的<h1>标签,那么在页面上 展示的效果是<h1>,utext 才会解析成一级标题
th:fragment声明 HTML 代码片段。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值