24

Spring Boot 2.x基础教程:使用 Thymeleaf开发Web页面

 4 years ago
source link: http://blog.didispace.com/spring-boot-learning-21-4-1/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

通过本系列教程的前几章内容(API开发、数据访问)。我们已经具备完成一个涵盖数据存储、提供HTTP接口的完整后端服务了。依托这些技能,我们已经可以配合前端开发人员,一起来完成一些前后端分离的Web项目,或是一些小程序、或者是App之类的应用开发。

对于Web项目来说,前后端分离模式是目前最为流行的,主要得益于前端框架的完善以及前后端分离方案的日渐成熟。这样的实现模式帮助Web类产品的开发团队更好的拆分任务,以及让开发人员更加聚焦在某一端的开发技术之上。所以,在本教程中,优先介绍了如何开发API,而不是开发Web页面。但是,传统模式的Web页面在一个项目中就可以管理,如果开发人员技能本身就可覆盖全栈,那直接采用传统模板引擎方式开发,也是个不错的选择。尤其对于一些老团队,对模板引擎非常熟悉,可以减少非常多的学习成本,直接上手Spring Boot来开发Web应用。

接下来,我们就来具体讲讲在Spring Boot应用中,如何使用Thymeleaf模板引擎开发Web页面类的应用。

静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

  • /static
  • /public
  • /resources
  • /META-INF/resources

举例:我们可以在 src/main/resources/ 目录下创建 static ,在该位置放置一个图片文件。启动程序后,尝试访问 http://localhost:8080/D.jpg 。如能显示图片,配置成功。

渲染Web页面

在之前的示例中,我们都是通过 @RestController 来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?

模板引擎

在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。

Spring Boot提供了自动化配置模块的模板引擎主要有以下几种:

  • Thymeleaf
  • FreeMarker
  • Groovy

当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为: src/main/resources/templates 。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

补充:Spring Boot从一开始就建议使用模板引擎,避免使用JSP。同时,随着Spring Boot版本的迭代,逐步的淘汰了一些较为古老的模板引擎。

Thymeleaf

Thymeleaf是本文我们将具体介绍使用的模板引擎。它是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

示例模板:

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</td>
      <th th:text="#{msgs.headers.price}">Price</td>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod : ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td>
    </tr>
  </tbody>
</table>

可以看到Thymeleaf主要以属性的方式加入到html标签中,浏览器在解析html时,当检查到没有的属性时候会忽略,所以Thymeleaf的模板可以通过浏览器直接打开展现,这样非常有利于前后端的分离。

动手试一下

第一步:新建一个Spring Boot应用,在 pom.xml 中加入所需的模板引擎模块,比如使用 thymeleaf 的话,只需要引入下面依赖:

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

第二步:创建一个Spring MVC的传统Controller,用来处理根路径的请求,将解决渲染到index页面上,具体实现如下

@Controller
public class HelloController {

    @GetMapping("/")
    public String index(ModelMap map) {
        map.addAttribute("host", "http://blog.didispace.com");
        return "index";
    }

}

简要说明:

  • 在渲染到index页面的时候,通过ModelMap,往页面中增加一个 host 参数,其值为 http://blog.didispace.com
  • return 的值index代表了要使用的模板页面名称,默认情况下,它将对应到 src/main/resources/templates/ 目录下的 index.html 模板页面

第三步:根据上一步要映射的模板,去模板路径 src/main/resources/templates 下新建模板文件 index.html ,内容如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

在该页面的body中,包含了一个带有Thymeleaf属性的h1标签,该便签内容将绑定 host 参数的值。

由于Thymeleaf通过属性绑定的特性。该模板页面同其他模板引擎不同,直接通过浏览器打开html页面,它是可以正常运作的,将会直接展现Hello World标题。这有利于开发页面的时候可以在非启动环境下验证应前端样式的正确性。

如果启动程序后,访问 http://localhost:8080/ ,上面页面就会展示Controller中host的值: http://blog.didispace.com ,做到了不破坏HTML自身内容的数据逻辑分离。

更多Thymeleaf的页面语法,可以访问Thymeleaf的官方文档来深入学习使用。

Thymeleaf的配置参数

如有需要修改默认配置的时候,只需复制下面要修改的属性到 application.properties 中,并修改成需要的值:

# Enable template caching.
spring.thymeleaf.cache=true 
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true 
# Content-Type value.
spring.thymeleaf.content-type=text/html 
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true 
# Template encoding.
spring.thymeleaf.encoding=UTF-8 
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names= 
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5 
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/ 
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html  spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

举几个我们常用的配置内容:

Q:不想每次修改页面都重启

A:修改 spring.thymeleaf.cache 参数,设置为 false

Q:不想使用template目录存放模板文件

A:修改 spring.thymeleaf.prefix 参数,设置为你想放置模板文件的目录

Q:不想使用index作为模板文件的扩展名

A:修改 spring.thymeleaf.suffix 参数,设置为你想用的扩展名

Q:HTML5的严格校验很烦人

A:修改 spring.thymeleaf.mode 参数,设置为 LEGACYHTML5

更多本系列免费教程连载「点击进入汇总目录」

代码示例

本文的相关例子可以查看下面仓库中的 chapter4-1 目录:

如果您觉得本文不错,欢迎 Star 支持,您的关注是我坚持的动力!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK