Spring Boot 学习(2)引入模板引擎(Thymeleaf)

写在前面:最近利用晚上的时间在网上看视频学习SpringBoot,这博客是对学习的一点点总结及记录,技术是开源的、知识是共享的
如果你对Spring Boot 感兴趣,可以关注我的动态,我们一起学习。用知识改变命运,让家人过上更好的生活

一、Thymeleaf 介绍

1. 什么是 Thymeleaf

Thymeleaf 是 Web 和独立环境的现代服务器端 Java 模板引擎,能够处理HTML,XML,JavaScript,CSS 甚至纯文本。

2. Thymeleaf 的优点

  1. 开箱即用。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果。并且开发人员也可以扩展和创建自定义的方言;
  2. Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
  3. 便捷性:可以让前端开发人员在浏览器中直接打开查看样式,也可以让后端开发人员根据真实数据查看显示的效果。同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案。

从 Jsp 到 Thymeleaf,再到目前很火的 vue,这是一个逐渐实现前后端分离的过程。jsp的特点是在页面里面可以写 java代码,这样就会使静态页面和逻辑混在一起,维护性将会很差。自从有了 Thymeleaf,基本解决了问题(还是未实现前后台分离),因为 Thymeleaf 支持html,将静态页面和业务逻辑进行整合,由服务器端渲染之后返回客户端进行显示。如今各大公司采用的 vue,才算实现了真正意义上的前后端分离,使得前端开发人员专注于前台界面的开发,后端开发人员专注于后台接口的开发。

二、Spring Boot 整合 Thymeleaf

1. 引入thymeleaf;

创建好的项目,在pom.xml 中添加以下依赖

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

或者在最初创建项目的时候,添加 Thymeleaf

在这里插入图片描述

2. 编写controller

@Controller
public class HelloController {

    /**
     * 查出数据并展示在页面
     *
     * @return
     */
    @RequestMapping("/success")
    public String success(Map<String, Object> map) {
        map.put("name", "<h1>扬帆向海</h1>");
        map.put("employees", Arrays.asList("程序员", "架构师", "项目经理"));
        return "success";
    }

}

3. 编写 success.html

注意:success.html 最上面要引入 thymeleaf 名称空间。
xmlns:th=“http://www.thymeleaf.org”

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>欢迎访问thymeleaf页面</h1>
    <hr/>

    <!--  th:text 将div里面的文本设置为某个值  -->
    <div id=div01 class="myDiv" th:id="${name}" th:class="${name}" th:text="${name}"></div>
    <hr/>
    
    <div th:text="${name}"></div>
    <!-- th:utext 不会转义特殊字符 -->
    <div th:utext="${name}"></div>
    <hr/>

    <h4 th:text="${employee}" th:each="employee:${employees}"></h4>
    <hr/>

    <h4>
        <span th:each="employee:${employees}"> [[${employee}]] </span>
    </h4>
</body>
</html>

th:each 指令来遍历一个集合

th:text 指令进行数据的展示

th:text 指令会转义特殊字符

th:utext 指令不会转义特殊字符

4. 所有的配置完成后,启动项目

访问 http://localhost:8080/success

在这里插入图片描述

发布了73 篇原创文章 · 获赞 795 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43570367/article/details/103603966