SpringBoot-04-thymeleaf模板


前言

参考自:https://www.cnblogs.com/hellokuangshen/p/12516870.html


一、什么是模板引擎?

模板引擎是为了使用户界面与业务数据分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的文档。

JSP就是一个模板引擎。

JSP有什么特点呢?

  • jsp文件允许同时使用html和java语言编写并生成动态网页。

故我们可以总结一下,模板引擎就是

  • 使用符合特定规范的格式文本
  • 生成特定格式的文档(如html)

那么为什么要学thymeleaf模板呢?

  1. SpringBoot以jar的方式打包项目,不是war;
  2. SpringBoot使用嵌入式的Tomcat,默认不支持jsp。

二、引入thymeleaf依赖

使用Maven,添加依赖

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

如果在html文件中导入命名空间的约束,编写代码的时候会提示补全,方便我们使用。

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

三、thymeleaf语法

所有的html元素都可以被thymeleaf替换接管,用th :元素名,如th:text=""

1.基础功能:传值取值

thymeleaf模板如何接收controller传递的值?使用Model

第一步,新建GetValue.html
使用<div th:text="${msg}"></div>接收并展示Controller层传递的数据。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>getValue</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>

第二步,新建Controller,
使用model.addAttribute("msg","getValue");传值给View层。

@Controller
@RequestMapping("/helloThymeleaf")
public class helloThymeleaf {
    @RequestMapping("/getValue")
    public String getValue_html(Model model){
        model.addAttribute("msg","getValue");
        return "getValue";
    }
}

在这里插入图片描述

运行Application类,访问链接http://localhost:8080/helloThymeleaf/getValue,效果图如下:
在这里插入图片描述
注意:Session和Model的区别

区别 1. session 里放的数据可以在其他页面使用
区别 2. model的数据,只能在接下来的页面使用,其他页面就不能使用

2.转义字符串为标签

如果我们传递的msg为<h1>getValue</h1>这种带有html标签的字符串,则该字符串有两种解释方法:

1.显示为文本<h1>getValue</h1>
2.显示为标题一格式的getValue

如何使传递的字符串<h1>被认为是标签呢?只需要使用th:utext="${msg}"即可。

修改getValue.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>getValue</title>
</head>
<body>
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
</body>
</html>

修改Controller类helloThymeleaf.java

@Controller
@RequestMapping("/helloThymeleaf")
public class helloThymeleaf {
    @RequestMapping("/getValue")
    public String getValue_html(Model model){
        model.addAttribute("msg","<h1>getValue</h1>");
        return "getValue";
    }
}

运行后显示
在这里插入图片描述

3.for-each遍历功能

Controller层发送一个List

model.addAttribute("pets", Arrays.asList("cat","dog","pig"));

Arrays.asList("cat","dog","pig")该方法是将数组转化成List集合的方法,用此方法得到的List的长度是不可改变的。

View层遍历这个List

<ol>
    <li th:each="pet:${pets}" th:text="${pet}"></li>
</ol>

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

posted @ 2023-01-10 18:50  对CSDN使用炎拳吧  阅读(50)  评论(0编辑  收藏  举报