3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

要使用thymeleaf做页面模板,需要两步。

一、添加依赖

二、进行配置(需要定制化的时候就需要配置)

一、在pom.xml中添加如下代码:

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

    </dependency>

二、点击: Spring Boot Reference Guide

然后ctrl + F搜索 ,输入spring.thymeleaf.prefix,如下就是定位到的配置内容:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

配置内容需要放在配置文件中,spring-boot默认的配置文件为 application.properties ,配置文件需要放在文件夹中,因此我们新建source folder

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

输入 src/main/resources ,完成之后,如下图

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

于是,在此文件夹下新建文件 application.properties,在其中填入如下代码:

spring.thymeleaf.cache=false # Enable template caching.
spring.thymeleaf.content-type=text/html # Content-Type value.
spring.thymeleaf.enabled=true # Enable MVC Thymeleaf view resolution.
spring.thymeleaf.encoding=UTF-8 # Template encoding.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.

spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.

现在先看一下包结构:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

因此,在名为src/main/resources  的 sources folder 下新建名为 templates 的 folder,用来存放我们的页面模板,要注意,sources folder 和 folder 长得是不一样的,如下图:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

在templates下新建文件hello.html,然后加入如下代码:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

然后在DemoController.java类中加入如下代码:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

然后启动应用,but,报错了,如下:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

这是将hello.html中的3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)修改为:3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

这只解决了一部分问题,是因为applicatin.properties文件中多了不需要的内容(后面的注释前面有个空格),删除多余的注释,如下:

spring.thymeleaf.cache=false
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/

spring.thymeleaf.suffix=.html

然后,启动应用,访问 http://localhost:8080/demo/thymeleaf ,但是,还有错:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

在定位console输出的异常信息:

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

故解决问题,在hello.html中添加代码: </meta> ,原来使用eclipse新建的html文件中默认是没有</meta>的。修改之后,再次访问,则访问成功.

3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)