【SpringBoot】 4 Thymeleaf

官网

https://www.thymeleaf.org/

介绍

Thymeleaf 是一个适用于 Web 和独立环境的现代服务器端 Java 模板引擎。

模板引擎:为了使用户界面和业务数据分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎会生成一个标准的 html 文档。

模板的作用:做好一个模板后,套入对应的位置的数据,最终以 html 的格式进行展示。

模板引擎的特点:提高页面、代码的复用性。

官网文档

https://www.thymeleaf.org/doc/tutorials/3.1/thymeleafspring.html

依赖

pom.xml

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置

thymeleaf 的默认配置,可以不改。

application.yml

yml 复制代码
spring:
  application:
    name: system
  thymeleaf:
    prefix: classpath:/templates/ #前缀,默认为classpath:/templates/    
    suffix: .html #后缀,默认为.html

接口

在 controller 目录下,新建 UserController 类。

此处返回的是 user 页面。

UserController.java

java 复制代码
package com.lm.system.controller;

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

/**
 * @Author: DuHaoLin
 * @Date: 2024/7/26
 */
@Controller
public class UserController {

    @GetMapping("user")
    public String user(Model model) {
        model.addAttribute("name", "Tom");
        model.addAttribute("age", 18);
        return "user";
    }

}

返回页面

在 resource 目录下,新建 thymeleaf 默认获取的 templates 目录。

在 templates 目录下,新建 user.html 文件。

user.html

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf</title>
</head>
<body>
    <span>姓名:</span>
    <span th:text="${name}"></span>
    <br />
    <span>年龄:</span>
    <span th:text="${age}"></span>
</body>
</html>

效果图展示

项目目录结构

相关推荐
xiaobaoyu4 分钟前
ssm
后端
Nick_zcy6 分钟前
小说在线阅读网站和小说管理系统 · 功能全解析
java·后端·python·springboot·ruoyi
源码宝9 分钟前
基于 SpringBoot + Vue 的医院随访系统:技术架构与功能实现
java·vue.js·spring boot·架构·源码·随访系统·随访管理
王中阳Go18 分钟前
2026年了,还在纠结后端转AI要不要死磕Python?试试Go吧
后端·go·ai编程
用户83562907805129 分钟前
用 Python 轻松在 Excel 工作表中应用条件格式
后端·python
red1giant_star33 分钟前
Python根据文件后缀统计文件大小、找出文件位置(仿Everything)
后端·python
长大198839 分钟前
每秒10万写入的订单系统:MySQL分库分表、缓冲设计、批量写入优化实战
后端
渐儿1 小时前
缓存一致性与分布式锁:工程踩坑全解
后端
长大19881 小时前
为什么我加了索引,查询反而更慢了?
后端
阿聪谈架构1 小时前
第08章:MCP 模型上下文协议(下)
人工智能·后端