SpringBoot_Thymeleaf 基础

SpringBoot_Thymeleaf 基础

什么是Thymeleaf

Thymeleaf官方是这么说的 Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf 是一个现代服务器端 Java 模板引擎 用于Web技术和独立环境

什么是模板引擎?

模板引擎是为了使用户界面与业务数据分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的html文档。从字面上理解模板引擎,最重要的就是模板二字,这个意思就是做好一个模板后套入对应位置的数据,最终以html的格式展示出来,这就是模板引擎的作用。

就好比 如果自己做饭吃和点外卖一个道理

​ 如果是自己做饭在每次做饭时都需要自己去准备食材已经自己去动手做 而点外卖我们只需要下载软件就可以点外卖,在这里点外卖软件就相当于一个模板引擎如果需要吃饭的时候只需要去下单即可,Thymeleaf就是一个模板引擎。

​ 当然在JavaWeb中这种模板引擎不止Thymeleaf一个,比如在之前学过的JSP 也是一个模板引擎,而且还是官方标准的,但是由于JSP缺点多而且无法直接被客户端(浏览器)直接识别,所以出现了很多第三方的模板引擎比如Thymeleaf、FreeMaker、Velocity

听完了模板引擎的介绍,相信你也很容易明白了模板引擎在web领域的主要作用:让网站实现界面和数据分离,这样大大提高了开发效率,让代码重用更加容易。

介绍Thymeleaf

Thymeleaf 是一个现代服务器端 Java 模板引擎,既适用于 web 环境,也适用于独立环境,能够处理 HTML、 XML、 JavaScript、 CSS 甚至纯文本。

主要目标是提供一种优雅的、高度可维护的创建模板的方法(低耦合)。Thymeleaf 允许处理六种模板,每种模板称为模板模式: HTML XML Text JavaScript CSS RAW 有两种标记模板模式(HTML 和 XML)、三种文本模板模式(TEXT、 JAVASCRIPT 和 CSS)和无操作模板模式(RAW)。

  • 动静分离: Thymeleaf选用html作为模板页,这是任何一款其他模板引擎做不到的!Thymeleaf使用html通过一些特定标签语法代表其含义,但并未破坏html结构,即使无网络、不通过后端渲染也能在浏览器成功打开,大大方便界面的测试和修改。

  • 动静分离: Thymeleaf选用html作为模板页,这是任何一款其他模板引擎做不到的!Thymeleaf使用html通过一些特定标签语法代表其含义,但并未破坏html结构,即使无网络、不通过后端渲染也能在浏览器成功打开,大大方便界面的测试和修改。

  • Springboot官方大力推荐和支持,Springboot官方做了很多默认配置,开发者只需编写对应html即可,大大减轻了上手难度和配置复杂度。

开始学习Thymeleaf

在学习使用Thymeleaf之前我们必须有一定的SpringBoot的基础,因为我们使用Thymeleaf时大多数是基于SpringBoot环境

01.引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

02.创建Controller层

@Controller //声明这个类是一个Contorller 并且注册进Spring容器
@Slf4j
public class TestController {
    @RequestMapping(value = "/test" ,method = RequestMethod.GET) //请求地址
    public String test01(Model model){
        log.info("接收到请求...."); //控制台日志打印
        model.addAttribute("username","张三"); //往域对象中存值
        model.addAttribute("msg1","thymeleaf 普通存值取值");
        return "index"; //与Templates中index.html对应
    }
}

03.编写前端页面

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"> <!--引入thymeleaf规则-->
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf_Index</title>
</head>
<body>
    <!--首先这不是el表达式 而是ognl表达式 只是语法糖很像-->
    <h1 th:text="${msg1}">null</h1> <!--默认值为null -->
    <h2 th:text="${username}">null</h2>
</body>
</html>

04.编写配置文件

# THYMELEAF (ThymeleafAutoConfiguration)
# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=true
# 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template=true
# 检查模板位置是否正确(默认值 :true )
spring.thymeleaf.check-template-location=true
#Content-Type 的值(默认值: text/html )
spring.thymeleaf.content-type=text/html
# 开启 MVC Thymeleaf 视图解析(默认值: true )
spring.thymeleaf.enabled=true
# 模板编码
spring.thymeleaf.encoding=UTF-8
# 要被排除在解析之外的视图名称列表,⽤逗号分隔
spring.thymeleaf.excluded-view-names=
# 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5)
spring.thymeleaf.mode=HTML5
# 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ )
spring.thymeleaf.prefix=classpath:/templates/
# 在构建 URL 时添加到视图名称后的后缀(默认值: .html )
spring.thymeleaf.suffix=.html

###Thymeleaf所有的配置选项####
spring.thymeleaf.cache=true #是否启用缓存
spring.thymeleaf.check-template=true # 是否在模板展示之前检查模板是否存在
spring.thymeleaf.check-template-location=true # 是否检查模板位置是否存在
spring.thymeleaf.enabled=true #是否检查框架已经thymeleaf视图解析
spring.thymeleaf.enable-spring-el-compiler=false # 在SpringEL表达式中启用SpringEL编译器。
spring.thymeleaf.encoding=UTF-8 # 设置页面的编码.
spring.thymeleaf.excluded-view-names= # 要被排除在解析之外的视图名称列表,⽤逗号分隔
spring.thymeleaf.mode=HTML # # 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5)
spring.thymeleaf.prefix=classpath:/templates/ # 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ )
spring.thymeleaf.reactive.chunked-mode-view-names= # 允许解析视图名称列表
spring.thymeleaf.reactive.full-mode-view-names= # 
spring.thymeleaf.reactive.max-chunk-size=0 # 用于写入响应的数据缓冲区的最大大小,以字节为单位。
spring.thymeleaf.reactive.media-types= # 视图技术支持的媒体类型。
spring.thymeleaf.servlet.content-type=text/html # Content-Type 的值(默认值: text/html )
spring.thymeleaf.suffix=.html # 在构建 URL 时添加到视图名称后的后缀(默认值: .html )
spring.thymeleaf.template-resolver-order= # 模板解析器在链中的顺序。
spring.thymeleaf.view-names= # 允许解析视图名称列表用(逗号隔开)

05.查看结果

​ 在运行程序前先看一下前端页面
在这里插入图片描述

​ 可以看到页面显示的是设置好的默认值 NULL,然后我们启动后台服务在看一下
在这里插入图片描述

​ 到此为止就已经学会了基本的Thymeleaf使用了,接下来就进入更深一层学习一些其他的语法

  1. th:href 替换链接

    <input th:id="${user.id}"/>
    
  2. th:src 替换资源路径

    <script type="text/javascript" th:src="@{a.js}"></script>
    
  3. th:value 替换值

     <input th:value="${user.name}" >
    
  4. th:text 替换文本

    <p th:text="${user.name}">CodeWYX</p>
    
  5. th:id 替换id

    <input th:id="${user.id}"/>
    
  6. th:object 替换对象

    <div th:object="${user}"></div>
    
  7. th:utext 支持html的文本替换

    <p utext:="${htmlcontent}">content</p>
    
  8. th:each 迭代

    <tr th:each="u:${user}" >
    

现在我们就来使用一下上面所说的语法

01.在原有的Controller上进行增加

@Controller
@Slf4j
public class TestController {

    @RequestMapping(value = "/test" ,method = RequestMethod.GET)
    public String test01(Model model){
        log.info("接收到请求....");

        HashMap<String, Object> map = new HashMap<>();
        map.put("MapKey","MapValue");

        ArrayList<Object> list = new ArrayList<>();
        list.add("你好");
        list.add("世界");

        User user = new User();
        user.setId(1);
        user.setName("李四");
        user.setAge(19);

        model.addAttribute("username","张三");
        model.addAttribute("msg1","thymeleaf 普通存值取值");
        model.addAttribute("map",map);
        model.addAttribute("list",list);
        model.addAttribute("user",user);

        return "index";
    }
}

02.修改前端页面

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf_Index</title>
</head>
<body>
    <!--首先这不是el表达式 而是ognl表达式 只是语法糖很像-->
    <h1 th:text="${msg1}">null</h1> <!--默认值为null -->
    <h2 th:text="${username}">null</h2>
    <h2 th:text="${map.get('MapKey')}"/><!--注意这里取值的key不能使用双引号-->
    <!--遍历list集合中的值-->
    <table>
        <tr th:each="l:${list}">
            <td th:text="${l}"></td>
        </tr>
    </table>
    <!--遍历map的值 01-->
    <table>
        <tr th:each="i:${map}">
            <td th:text="${i.getKey()}">
            </td>
            <td th:text="${i.getValue()}">

            </td>
        </tr>
    </table>

    <!--遍历map的值 02-->
    <table>
        <tr th:each="i:${map}">
            <td th:text="${map.get(i.getKey())}">
            </td>
        </tr>
    </table>

    <!--取出JavaBean中的值-->
    <h2 th:text="${user.getId()}"></h2>
    <h2 th:text="${user.getName()}"></h2>
    <h2 th:text="${user.getAge()}"></h2>
</body>
</html>

03.查看页面显示
在这里插入图片描述

到此我们的Thymeleaf的学习就已经学完了,当然还有一点需要补充的就是我们除了使用${…}以外还可以使用*{…}和使用#{…}来读取配置文件的数据

案例:

spring.messages.basename=templates/index #配置

新建一个templates/index.properties

index.name=lisi
index.age=19

前端页面使用#{…}读取

 <h2 th:text="#{index.age}"></h2>
 <h2 th:text="#{index.name}"></h2>

{…}以外还可以使用*{…}和使用#{…}来读取配置文件的数据

案例:

spring.messages.basename=templates/index #配置

新建一个templates/index.properties

index.name=lisi
index.age=19

前端页面使用#{…}读取

 <h2 th:text="#{index.age}"></h2>
 <h2 th:text="#{index.name}"></h2>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeWYX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值