Spring Boot(六)springboot模板引擎——Thymeleaf

一、Thymeleaf简介

  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

二、Thymeleaf 文件在SpringBoot项目中的位置

  位于resources目录下的templcates文件夹下。

在这里插入图片描述

三、使用Thymeleaf前提条件

  1. 创建SpringBoot项目是勾选Thymeleaf

在这里插入图片描述

  1. 在html文件上方<html lang="en">加上xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<!--
    xmlns:th="http://www.thymeleaf.org"
    xmlns:是一个命名空间
    地址是thymeleaf的规则文件
-->
<!--
    项目中包含thymeleaf依赖,他会根据thymeleaf自定义的标签名称,
    获取后台数据
-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1 th:text="${data}">thymeleaf模板引擎</h1>
    </body>
</html>

四、Thymeleaf表达式

  1. 标准表达式
<h2>thymeleaf标准表达式:${}</h2>
用户编号:<h3 th:text="${user.id}"></h3>
用户姓名:<h3 th:text="${user.name}"></h3>
用户住址:<h3 th:text="${user.address}"></h3>

  在控制层中,初始化了一个User对象,包含id、name、address属性,赋值后放入到Model中,在Thymeleaf页面中,直接使用标准表达式即可获取到数据。th:text是Thymeleaf的语法规则,表示表达式中的值会替代当前标签中的文本。

  1. 变量表达式(星号表达式)
<h2>thymeleaf变量表达式(星号表达式):*{}</h2>
<div th:object="${user}">
    用户编号:<h3 th:text="*{id}"></h3>
    用户姓名:<h3 th:text="*{name}"></h3>
    用户住址:<h3 th:text="*{address}"></h3>
</div>

  使用th:object表示${}是一个对象,在它的字标签中可以直接使用星号表达式——*{},直接显示属性的值。

  1. URL路径表达式
<h1>URL路径表达式:@{......}</h1>

<h2>a标签中的绝对路径(无参数):</h2>
<a href="http://www.baidu.com">传统方法跳转至百度</a><br>		<!-- 与下一行代码功能相同 -->
<a th:href="@{https://blog.csdn.net/ccccc_chuang}">跳转至krain</a><br>

<a href="http://localhost:8080/user/detail">传统方法跳转至/user/detail</a><br>		<!-- 与下一行代码功能相同 -->
<a th:href="@{http://localhost:8080/user/detail}">跳转至/user/detail</a><br>

<h2>相对路径(无参数)</h2>
<a th:href="@{/user/detail}">跳转至/user/detail</a><br>

<h2>绝对路径(一个参数)</h2>
<a href="http://localhost:8080/test?username=zhangsan">绝对路径(带一个参数)</a><br>	   <!-- 与下一行代码功能相同 -->
<a th:href="@{http://localhost:8080/test?username=zhangsan}">相对路径(带一个参数)</a>

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

<h2>相对路径(从后台获取参数)</h2>
<a th:href="@{'/test?username='+${name}}">相对路径(带一个参数)</a>

<h2>相对路径(从后台获取参数)</h2>
<a th:href="@{'/test1?id='+${id}+'&username='+${name}+'&address='+${address}}">相对路径(从后台获取参数)</a><br>	<!-- 与下一行代码功能相同 -->
<a th:href="@{/test1(id=${id},username=${name},address=${address})}">相对路径(从后台获取参数),该方式推荐使用</a>

<h2>相对路径restful</h2>
<a th:href="@{'/test3/'+${id}}">相对路径restful1</a><br>		<!-- 与下一行代码功能相同 -->
<a th:href="@{'/test2/'+${id}+'/'+${name}}">相对路径restful2</a>

五、Thymeleaf常见属性

  1. th:each=""遍历Map、List、数组和混合型数据类型
  • 后台控制类代码
@Controller
public class UserController {

    @RequestMapping(value = "/each/list")
    public String list(Model model){
        List<User> userList = new ArrayList<User>();		//List集合
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId("100"+i);
            user.setName("xxx"+i);
            user.setAge("2"+i);
            user.setAddress("河南"+i);
            userList.add(user);
        }
        model.addAttribute("userList",userList);
        return "eachList";
    }

    @RequestMapping(value = "/each/map")
    public String map(Model model){
        HashMap<Integer, Object> map = new HashMap<>();		//Map集合
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId("200"+i);
            user.setName("yyy"+i);
            user.setAge("3"+i);
            user.setAddress("湖南"+i);
            map.put(i,user);
        }
        model.addAttribute("userMap",map);
        return "eachMap";
    }

    @RequestMapping(value = "/each/array")
    public String array(Model model){
        User[] users = new User[10];					//数组
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId("300"+i);
            user.setName("zzz"+i);
            user.setAge("4"+i);
            user.setAddress("海南"+i);
            users[i] = user;
        }
        model.addAttribute("userArray",users);
        return "eachArray";
    }

    @RequestMapping(value = "/each/all")
    public String eachAll(Model model) {
        //list -> Map -> List -> User		list中嵌套Map,Map中又嵌套List,List中又嵌套User对象
        List<Map<Integer, List<User>>> myList = new ArrayList<Map<Integer, List<User>>>();
        for (int i = 0; i < 2; i++) {
            Map<Integer,List<User>> myMap = new HashMap<Integer, List<User>>();
            for (int j = 0; j < 2; j++) {
                List<User> myUserList = new ArrayList<User>();
                for (int k = 0; k < 3; k++) {
                    User user = new User();
                    user.setId("400"+k);
                    user.setName("张三"+k);
                    user.setAge("5"+k);
                    user.setAddress("广州市"+i);
                    myUserList.add(user);
                }
                myMap.put(j,myUserList);
            }
            myList.add(myMap);
        }
        model.addAttribute("myList",myList);
        return "eachAll"; }
}
  • Thymeleaf代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>th:each 循环遍历数据</title>
</head>
<body>
    <h1>th:each 循环遍历 List 集合</h1>
    <div th:each="user,userStat:${userList}">			<!-- userStat表示当前变量的状态 -->
        <span th:text="${userStat.count}"></span>		<!-- ${userStat.count}表示该List数据的个数 -->
        <span th:text="${userStat.index}"></span>		<!-- ${userStat.count}表示该List当前数据的下表 -->
        <span th:text="${user.id}"></span>
        <span th:text="${user.name}"></span>
        <span th:text="${user.age}"></span>
        <span th:text="${user.address}"></span>
    </div>

    <h1>th:each 循环遍历 Map 集合</h1>
    <div th:each="user,userStat:${userMap}">
        <span th:text="${userStat.count}"></span>
        <span th:text="${userStat.index}"></span>
        <span th:text="${user.key}"></span>
        <span th:text="${user.value}"></span>
        <span th:text="${user.value.id}"></span>
        <span th:text="${user.value.name}"></span>
        <span th:text="${user.value.age}"></span>
        <span th:text="${user.value.address}"></span>
    </div>

    <h1>使用each遍历数组</h1>
    <div th:each="user,userStat:${userArray}">
        <span th:text="${userStat.index}"></span>
        <span th:text="${userStat.count}"></span>
        <span th:text="${user.id}"></span>
        <span th:text="${user.name}"></span>
        <span th:text="${user.age}"></span>
        <span th:text="${user.address}"></span>
    </div>

    <h1>list -> Map -> List -> User</h1>
    <div th:each="userMapList:${myList}">
        <div th:each="userListMap:${userMapList}">
            Map集合的key:<span th:text="${userListMap.key}"></span>
            <div th:each="userList:${userListMap.value}">
                <span th:text="${userList.id}"></span>
                <span th:text="${userList.name}"></span>
                <span th:text="${userList.age}"></span>
                <span th:text="${userList.address}"></span>
            </div>
        </div>
    </div>
</body>
</html>
  1. 条件判断属性的使用
  • 控制层
@Controller
public class JudgeController {
    @RequestMapping(value = "/judge")
    public String judge(Model model){
        model.addAttribute("sex",0);
        model.addAttribute("productType",1);
        model.addAttribute("flag",true);
        return "condition";
    }
}
  • Thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>条件判断</title>
</head>
<body>
    <h2>th:if  条件判断</h2>
    <div th:if="${sex eq 1}"></div>
    <div th:if="${sex eq 0}"></div>

    <h2>th:unless  与if相反</h2>
    <div th:unless="${sex ne 0}">定一个flag</div>
    <div th:unless="${sex ne 1}">定两个flag</div>

    <h2>th:switch</h2>
    <div th:switch="${productType}">
        <span th:case="0">产品0</span>
        <span th:case="1">产品1</span>
        <span th:case="*">无此产品</span>
    </div>
</body>
</html>
  1. 内敛表达式
@Controller
public class InlineController {
    @RequestMapping(value = "/inline")
    public String inline(Model model){
        model.addAttribute("data", "springboot data");
        return "inline";
    }
}

  在标签中加入th:inline="text"属性之后,直接可以在标签内使用[[${data}]]的方式显示后台数据。

  在script标签中加入th:inline="javascript"后,可以在脚本中使用[[${data}]]进行数据的显示。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>内敛表达式</title>
</head>
<body th:inline="text">     <!--一般直接在body标签中加入-->
    <h1> th:inline="text"  内敛文本表达式</h1>
    <div th:inline="text">
        数据:[[${data}]]
    </div>

    数据out:[[${data}]]

    <script type="text/javascript" th:inline="javascript">
        function showData() {
            alert([[${data}]]);
            alert("=====");
        }
    </script>

    <h1>th:inline="javascript"  内敛脚本表达式</h1>
    <div th:inline="javascript">
        <button onclick="showData()">显示数据</button>
    </div>
</body>
</html>
  1. Thymeleaf运算符
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>数字运算</title>
</head>
<body>
    <!--
        三元运算:表达式?”正确结果”:”错误结果”
        算术运算:+ , - , * , / , %
        关系比较:> , < , >= , <= ( gt , lt , ge , le )
        相等判断:== , != ( eq , ne )
    -->
    <h1>三元运算</h1>
    <span th:text="${sex eq 1 ? '' : ''}"></span>

    <h1>算术运算</h1>
    5-2=<span th:text="5-2"></span><br/>
    5+2=<span th:text="5+2"></span><br/>
    5*2=<span th:text="5*2"></span><br/>
    5/2=<span th:text="5/2"></span><br/>
    5%2=<span th:text="5%2"></span><br/>

    <h1>关系比较</h1>
    5>2为<span th:if="${5 gt 2}"></span><br/>
    5<2为<span th:unless="${5 lt 2}"></span><br/>
    2>=2为<span th:if="${5 ge 2}"></span><br/>
    2<=2为<span th:unless="${5 le 2}"></span><br/>

    <h1>相等判断</h1>
    2==2为<span th:if="${2 eq 2}"></span><br/>
    5!=2为<span th:if="${5 ne 2}"></span><br/>
</body>
</html>

  运行结果:

在这里插入图片描述

  1. Thymeleaf基本对象
@Controller
public class BaseController {

    @RequestMapping(value = "/baseObj")
    public String baseObj(HttpServletRequest request, Model model, String id){
        model.addAttribute("username","lisi");
        request.getSession().setAttribute("data","sessionData");
        return "index";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>基本表达式对象</title>
</head>
<body>
    <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">
        //获取协议名称
        var scheme = [[${#request.getScheme()}]];       //http

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

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

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

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

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

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

        alert(allPath);
    </script>
</body>
</html>
  1. Thymeleaf内置对象
@Controller
public class UserController {

    @RequestMapping(value = "/user")
    public String getUser(Model model){
        model.addAttribute("data","hello springboot");
        model.addAttribute("time", new Date());
        return "user";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>内置对象</title>
</head>
<body>
    <h2 th:text="${time}"></h2><br/>
    <h2 th:text="${#dates.format(time,'yyyy-MM-dd HH:mm:ss')}"></h2><br/>		<!--将时间格式化-->
    <h2 th:text="${data}"></h2><br/>
    <h2 th:text="${#strings.substring(data,0,10)}"></h2><br/>		<!--获取该字符串的0~10位的子串-->
    <h2 th:text="${#lists}"></h2><br/>					<!--用于操作list数据类型-->
</body>
</html>

  运行结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

krain.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值