Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。
是新一代 Java 模板引擎,它支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。
将模板(页面)和数据进行整合然后输出显示
在创建好的Springboot项目中的pom文件添加thymeleaf依赖
org.springframework.boot
spring-boot-starter-thymeleaf
在application.properties或者application.yml里配置相关内容
#开发时关闭缓存,不然没法看到实时页面 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
1.创建好实体类(User)
- package com.example.model;
-
- import lombok.Data;
-
- @Data
- public class User {
- private int id;
- private String name;
- private String pwd;
-
- }
2.在controller包下创建ThymeleafController类
- package com.example.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
-
-
- @Controller
- @RequestMapping("tpl")
- public class ThymeleafController {
- @GetMapping("thymeleaf")
- public String index(Model model){
- model.addAttribute("id","123");
- model.addAttribute("name","张三");
- model.addAttribute("pwd","abc");
- return "thymeleaf/index";
- }
- }
3.在templates目录下创建index.html文件

- "http://www.thymeleaf.org">
-
SpringBoot模版渲染 - "Content-Type" content="text/html;charset=UTF-8"/>
"'用户ID:' + ${id}"/>
"'用户名称:' + ${name}"/>
"'用户密码:' + ${pwd}"/>
这一条语句是必不可少
然后启动项目

项目启动成功
获取访问url


会生成如上访问地址,然后去浏览器里访问
最后: