Spring Boot(六)-- 整合 Thymeleaf

  随着 Spring Boot 的出现,前后端分离开发逐渐成为主流,这个时候我们开发时就不需要后端页面模板。但还是有些公司在使用前后端不分离的开发,这时候我们就需要使用到后端页面模板。然而,Spring Boot 也支持页面模板。

  Spring Boot 在早期是支持 Velocity 作为页面模板,现在的 Spring Boot 已经不再支持 Velocity 作为页面模板了,此刻主要支持的页面模板有 Thymeleaf 和 Freemarker。作为 Java 最基础的页面模板 Jsp ,Spring Boot 也是支持的,只是使用起来还是比较麻烦的。下面小编就以本文介绍 Spring Boot 整合 Thymeleaf 。

Thymeleaf 介绍

  相比于 Freemarker 、Jsp 而言,Thymeleaf 是新一代的 Java 模板引擎,通常我们称之为前端页面模板。因为 Thymeleaf 模板的后缀是 .html ,不同于 Freemarker 、Jsp 这一类必须要服务端解析之后才能显示出来的页面模板,Thymeleaf 不需要经过服务端的解析就可以显示出来。另外,由于 Thymeleaf 模板后缀为 .html ,可以直接被浏览器打开,因此,预览时非常方便。

整合 Thymeleaf

   Spring Boot 中整合 Thymeleaf 非常容易,只需要创建项目时添加 Thymeleaf依赖即可:
在这里插入图片描述
项目创建完成后,我们会在 pom.xml 配置文件中发现 Thymeleaf 的依赖自动加载进来了:

<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>

  对于 Thymeleaf 来讲,不仅仅能在 SpringBoot 中使用,也可以在其他的项目中使用,但是Spring Boot 对 Thymeleaf 提供了一整套的自动化配置方案,这一套配置类的属性在:org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties , 我们可以通过 连续按两下 shift 进行ThymeleafProperties 查询,部分源码如下:

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    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 = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
    private boolean cache;
    private Integer templateResolverOrder;
    private String[] viewNames;
    private String[] excludedViewNames;
    private boolean enableSpringElCompiler;
    private boolean renderHiddenMarkersBeforeCheckboxes;
    private boolean enabled;
    private final ThymeleafProperties.Servlet servlet;
    private final ThymeleafProperties.Reactive reactive;
    //....
}
  • 说明:
  •   1、首先通过 @ConfigurationProperties 注解,将 application.properties 前缀为 spring.thymeleaf 的配置和这个类中的属性绑定。
  •   2、前三个 static 变量定义了默认的编码格式、试图解析器的前缀、后缀等。
  •   3、从前三行配置中,我们可以看出来, Thymeleaf 模板的默认位置在 resources/templates 目录下,默认的后缀时 .html
  •   4、这些配置,如果开发者不自己提供,则使用默认的,如果自己提供,则在 application.properties 中以 spring.thymeleaf 为前缀的相关的配置

Thymeleaf 本身的自动化配置类,则是: org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,部分源码:

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}
  • @EnableConfigurationProperties:在自动化配置类中,首先导入 ThymeleafProperties。
  • @ConditionalOnClass:这个注解表示当前系统中存在 TemplateModeSpringTemplateEngine 这两个类时,当前的自动化配置类才会生效。(如果我们没有引入 Thymeleaf 的依赖,这两个类是没有的)

案例

 创建 controller

  我们不用任何配置,创建了 Controller 直接使用即可:

/**
 * 因为我们要返回的是页面,所以只能使用 @Controller
 */
@Controller
public class BookController {

    @GetMapping("/book")
    public String user(Model model) {
        List<Book> books = new ArrayList<>();
        books.add(new Book(1, "西游记", "吴承恩"));
        books.add(new Book(2, "三国演义", "罗贯中"));
        books.add(new Book(4, "红楼梦", "曹雪芹"));
        books.add(new Book(3, "水浒传", "施耐庵"));
        model.addAttribute("books", books);
        return "book";
    }
}

public class Book {
    private Integer id;
    private String name;
    private String author;
//此处省略有参无参构造器以及get 和 set方法
}

在 BookController 中返回逻辑视图名+数据,逻辑视图名为 book ,意思我们需要在 resources/templates 目录下提供一个名为 book.html 的 Thymeleaf 模板文件。

 创建 Thymeleaf 模板文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>book</title>
</head>
<body>
    <table style="border-collapse:collapse;" border="1">
        <tr>
            <td>编号</td>
            <td>书名</td>
            <td>作者</td>
        </tr>
        <tr th:each="book : ${books}">
            <td th:text="${book.id}"></td>
            <td th:text="${book.name}"></td>
            <td th:text="${book.author}"></td>
        </tr>
    </table>
</body>
</html>

  我们在使用 Thymeleaf 时,需要引入thymeleaf 名称空间: xmlns:th="http://www.thymeleaf.org/ , 它自动导入的有错误,我们需要自己进行修改。

然后启动项目,在浏览器中访问:http://localhost:8080/book ,结果如下:
在这里插入图片描述

附加

  Thymeleaf 也支持在 js 中直接获取 Model 中的变量。例如:我们在 BookController 中有一个变量放入到 Model 中:

@Controller
public class BookController {

    @GetMapping("/book")
    public String user(Model model) {
        List<Book> books = new ArrayList<>();
        books.add(new Book(1, "西游记", "吴承恩"));
        books.add(new Book(2, "三国演义", "罗贯中"));
        books.add(new Book(4, "红楼梦", "曹雪芹"));
        books.add(new Book(3, "水浒传", "施耐庵"));
        model.addAttribute("books", books);
        model.addAttribute("username", "yexiaomo");
        return "book";
    }
}

  在页面模板中,可以直接在 js 中获取到这个变量的值:

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

访问页面:
在这里插入图片描述
  本文主要向大家简单介绍了 Spring Boot 和 Thymeleaf 整合时的几个问题,如果大家想了解更多,大家可以阅读 Thymeleaf 官方文档学习 Thymeleaf 的更多用法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值