21.2.2 创建视图

按照传统的方式,Java Web 应用会使用 JSP 作为视图层的技术。但是,正如我在第 6 章所述,在这个领域有一个新的参与者。Thymeleaf 的原生模板比 JSP 更加便于使用,而且它能够让我们以 HTML 的形式编写模板。鉴于此,我们将会使用 Thymeleaf 来定义 Contacts 应用的 home 视图。

首先,需要将 Thymeleaf 添加到项目的构建中。在本例中,我使用的是 Spring 4,所以需要将 Thymeleaf 的 Spring 4 模块添加到构建之中。在 Gradle 中,依赖将会如下所示:

compile("org.thymeleaf:thymeleaf-spring4")

如果使用 Maven 的话,所需的依赖如下所示:

<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf-spring4</artifactId>
</dependency>

需要记住的是,只要我们将 Thymeleaf 添加到项目的类路径下,就启用了 Spring Boot 的自动配置。当应用运行时,Spring Boot 将会探测到类路径中的 Thymeleaf,然后会自动配置视图解析器、模板解析器以及模板引擎,这些都是在 Spring MVC 中使用 Thymeleaf 所需要的。因此,在我们的应用中,不需要使用显式 Spring 配置的方式来定义 Thymeleaf。

除了将 Thymeleaf 依赖添加到构建中,我们剩下所需要做的就是定义视图模板。程序清单 21.5 展现了 home.html,这是定义 home 视图的 Thymeleaf 模板。

程序清单 21.5 home 视图渲染了一个创建新联系人的表单以及展现联系人的列表
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Spring Boot Contacts</title>
    <link rel="stylesheet" th:href="@{/style.css}" />
  </head>

  <body>
    <h2>Spring Boot Contacts</h2>
    <form method="POST">
      <label for="firstName">First Name:</label>
      <input type="text" name="firstName"></input><br/>
      <label for="lastName">Last Name:</label>
      <input type="text" name="lastName"></input><br/>
      <label for="phoneNumber">Phone #:</label>
      <input type="text" name="phoneNumber"></input><br/>
      <label for="emailAddress">Email:</label>
      <input type="text" name="emailAddress"></input><br/>
      <input type="submit"></input>
    </form>

    <ul th:each="contact : ${contacts}">
      <li>
        <span th:text="${contact.firstName}">First</span>
        <span th:text="${contact.lastName}">Last</span> :
        <span th:text="${contact.phoneNumber}">phoneNumber</span>,
        <span th:text="${contact.emailAddress}">emailAddress</span>
      </li>
    </ul>
  </body>
</html>

它实际上是一个非常简单的 Thymeleaf 模板,分为两部分:一个表单和一个联系人的列表。表单将会 POST 数据到 ContactController 的 submit() 方法上,用来创建新的 Contact。列表部分将会循环列出模型中的 Contact 对象。

为了使用这个模板,我们需要对其进行慎重地命名并放在项目的正确位置下。因为 ContactController 中 home() 方法所返回的逻辑视图名为 home,因此模板文件应该命名为 home.html,自动配置的模板解析器会在指定的目录下查找 Thymeleaf 模板,这个目录也就是相对于根类路径下的 templates 目录下,所以在 Maven 或 Gradle 项目中,我们需要将 home.html 放到 “src/main/resources/templates” 中。

这个模板还有一点小事情需要处理,它所产生的 HTML 将会引用名为 style.css 的样式表。因此,需要将这个样式表放到项目中。

Last updated