整合视图层(Thymeleaf的使用)

Thymeleaf简介

Thymeleaf的意思是模板引擎,适用于Web和独立环境,能够处理HTML,XML,JavaScript,CSS甚至纯文本,类似于Velocity,FreeMaker等传统的java模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型.

它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。

事实上, Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染,例如我们在做邮件发送时,可以使用 Thymeleaf 作为邮件发送模板。

另外,由于 Thymeleaf 模板后缀为 .html,可以直接被浏览器打开,因此,预览时非常方便。

整合

首先进行创建项目

SpringBoot整合Thymeleaf非常容易,只需要在创建项目时加入Thymeleaf即可

创建完成后,它的pom文件如下:

当然,Thymeleaf不仅可以在SpringBoot当中使用,还可以用到其他地方,只是SpringBoot对于Thymeleaf提供了一整套的自动化配置方案, 这一套配置类的属性在org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties中,源码如下:

package com.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING =
            StandardCharsets.UTF_8;
    public static final String DEFAULT_PREFIX =
            "classpath:/templates/";
    public static final String DEFAULT_SUFFIX =
            ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = DEFAULT_PREFIX;
    private String suffix = DEFAULT_SUFFIX;
    private String mode = "HTML";
    private Charset encoding = DEFAULT_ENCODING;
    private boolean cache = true;
}

 首先通过@ConfigurationProperties注解,将application.properties前缀为spring.thymeleaf的配置和这个类中的属性进行绑定

前三个static变量定义的是:默认编码格式;视图解析器前缀;后缀;

从前三行的配置中可以看出,Thymeleaf模板的默认位置是在resources/templates的目录下,默认的后缀是.html

这些配置如果自己提供,则在application.properties中以spring.thymeleaf为前缀开始进行相关配置,如果不自己提供,则使用默认的

我们刚才提到的SpringBoot为Thymeleaf提供了自动化配置类,则是org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,源码如下:

package com.example.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}

我们可以看到在这个自动化配置类中,首先导入的是ThymeleafProperties,然后@ConditionalOnClass注解表示当前系统中存在TemplateMode和springTemplateEngine类时,当前的自动化配置类才会生效,所以只要引入了Thymeleaf相关的依赖,这个配置就会生效

这些默认的配置我们几乎不需要做任何更改就可以直接进行使用,如果开发者有特殊需求,则可以在application.properties中配置以spring.thymeleaf为前缀的属性

接下来我们创建Controller,实际上在我们引入了Thymeleaf的依赖之后,我们可以不用做任何的配置了,新建的IndexController如下:

package com.example.controller;

import com.example.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId((long) i);
            u.setName("大黄:" + i);
            u.setAddress("济南:" + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "index";

    }
}

@Data
@Accessors(chain = true)
public class User {
    private Long id;
    private String name;
    private String address;
}

在IndexController中返回逻辑视图名和数据,逻辑视图名为index,意思是我们需要在resources/templates目录下创建一个index.html的Thyleaf模板文件

创建Thymeleaf

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>地址</td>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.address}"></td>
    </tr>
</table>
</body>
</html>

在Thymeleaf中,通过th:each指令来遍历一个集合,数据的展示通过th:text的指令来实现

注意index.html最上面要引入thymeleaf名称文件

配置完成后,就可以启动项目了,访问/index接口,就能看到集合中的数据了

另外Thymeleaf支持js中直接获取Model中的变量,例如在IndexController中有一个变量username:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("username", "李四");
        return "index";
    }
}

通过页面模板,可以直接在js中获取到这个变量

<script th:inline="javascript">
    var username = [[${username}]];
    console.log(username)
</script>

手动渲染

上面我们说返回一个Thymeleaf模板,我们也可以手动渲染Thymeleaf模板,一般在发送邮件时使用,例如我们在resources/templates目录下新建一个邮件模板mail.html,如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>hello 欢迎 <span th:text="${username}"></span>加入 XXX 集团,您的入职信息如下:</p>
<table border="1">
    <tr>
        <td>职位</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>薪水</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
<img src="http://www.javaboy.org/images/sb/javaboy.jpg" alt="">
</body>
</html>

在这个模板中有几个变量,我们要将这个HTML模板渲染成一个String字符串,再把这个字符串通过邮件的方式发送出去,那么该如何进行手动渲染呢?

package com.example;

import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@SpringBootTest
class mail {
    @Autowired
    TemplateEngine templateEngine;
    @Test
    void test1(){
        Context context = new Context();
        context.setVariable("username", "javaboy");
        context.setVariable("position", "Java工程师");
        context.setVariable("salary", 99999);
        String mail = templateEngine.process("mail", context);
        
        System.out.println(mail);
    }
}

在渲染时,我们需要首先注入一个TemplateEngine对象,这个对象在Thymeleaf的自动化配置类中配置的(即当我们引入Thymeleaf这个依赖之后,这个实例就有了)

然后构造一个Context对象用来存放变量

调用process方法进行渲染,该方法的返回值就是渲染之后的HTML字符串,然后我们将这个字符串发送回去

以上内容就是Spring Boot整合Thymeleaf的几个关键点,希望能够帮助到大家

  • 36
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 55
    评论
当前课程中商城项目的实战源码是我发布在 GitHub 上的开源项目 newbee-mall (新蜂商城),目前已有 9900 多个 Star,本课程是一个 Spring Boot 技术栈的实战类课程,课程共分为 3 大部分,前面两个部分为基础环境准备和相关概念介绍,第三个部分是 Spring Boot 商城项目功能的讲解,让大家实际操作并实践上手一个大型的线上商城项目,并学习到一定的开发经验以及其中的开发技巧。商城项目所涉及的功能结构图整理如下: 作者寄语本课程录制于2019年,距今已有一段时间。期间,Spring Boot技术栈也有一些版本升级,比如Spring Boot 2.7.x发版、Spring Boot 3.x版本正式版本。对于这些情况,笔者会在本课程实战项目的开源仓库中创建不同的代码分支,保持实战项目的源码更新,保证读者朋友们不会学习过气的知识点。新蜂商城的优化和迭代工作不会停止,不仅仅是功能的优化,在技术栈上也会不断的增加,截止2023年,新蜂商城已经发布了 7 个重要的版本,版本记录及开发计划如下图所示。 课程特色 对新手开发者十分友好,无需复杂的操作步骤,仅需 2 秒就可以启动这个完整的商城项目最终的实战项目是一个企业级别的 Spring Boot 大型项目,对于各个阶段的 Java 开发者都是极佳的选择实践项目页面美观且实用,交互效果完美教程详细开发教程详细完整、文档资源齐全代码+讲解+演示网站全方位保证,向 Hello World 教程说拜拜技术栈新颖且知识点丰富,学习后可以提升大家对于知识的理解和掌握,可以进一步提升你的市场竞争力 课程预览 以下为商城项目的页面和功能展示,分别为:商城首页 1商城首页 2购物车订单结算订单列表支付页面后台管理系统登录页商品管理商品编辑

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

是Lay

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

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

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

打赏作者

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

抵扣说明:

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

余额充值