SpringBoot 整合thymeleaf

1.Thymeleaf介绍(官网推荐:https://www.thymeleaf.org/doc/articles/thymeleaf3migration.html)

Thymeleaf是跟Velocity、FreeMarker类似的模板引擎,它可以完全替代JSP,相较与其他的模板引擎,它主要有以下几个特点:

(1) Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

(2) Thymeleaf开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

(3) Thymeleaf提供spring标准方言和一个与SpringMVC完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

2.引入依赖

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

3.基础设置

#开发时关闭缓存,不不然没法看到实时⻚页⾯面
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#编码
spring.thymeleaf.encoding=UTF-8
#类型
spring.thymeleaf.content-type=text/html
#名称的后缀
spring.thymeleaf.suffix=.html

4.HTML模板(src/main/resources/templates/tl/thymeleaf.html)

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Springboot 整合thymeleaf
<p th:text = "${userAttribute.id}" ></p>
<p th:text = "${userAttribute.username}" ></p>
</body>
</html>

5.新建 ThymeleafController

package com.xiaobing.demo001.controller;

import com.xiaobing.demo001.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("thymeleaf")
public class ThymeleafController {

    User user = new User(002,"武大","123456");
    @GetMapping("test_tl")
    public  String test(ModelMap modelMap){
        modelMap.addAttribute("userAttribute",user);
        return "tl/thymeleaf";
    }
}

6.启动项目

7.web访问

 --------------------------------------  亲测,学习笔记-----------------------------------

原文地址:https://www.cnblogs.com/xiaozhaoboke/p/14653006.html