SpringBoot集成Thymeleaf模板

1、添加起步依赖:

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

2、添加配置(application.properties):

#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false

参考ThymeleafProperties.java类,cache默认为true,其它属性都有默认值,一般不需要修改。

3、写测试controller返回页面并携带数据:

package cn.mmweikt.es.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {
    @GetMapping("/index")
    public String indexPage(Model model) {
        model.addAttribute("name", "es_project.");
        return "index";
    }
}

4、在resources/templates下放.html页面,在resources/static下放静态文件。templates和static下都可以再放文件夹:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span th:text="${name}"></span>
</body>
</html>

注意,在html标签里一定要引入 xmlns:th="http://www.thymeleaf.org" ,这样thymeleaf模板才会启用,才能使用th:*这样的语法。
语法可参考:
https://www.cnblogs.com/jin-zhe/p/8202885.html
https://www.cnblogs.com/nfcm/p/7843935.html

补充:
网上看到说,在spring-boot1.4之后,支持thymeleaf3,可以更改版本号来进行修改支持。3相比2极大的提高了效率,并且不需要标签闭合,类似的link,img等都有了很好的支持,按照如下配置即可:

 <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <!-- set thymeleaf version -->
     <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
     <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
     <!--set java version-->
     <java.version>1.8</java.version>
  </properties>
posted @ 2019-01-07 22:57  发挥哥  阅读(729)  评论(0编辑  收藏  举报