【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>

效果图展示

项目目录结构

相关推荐
云烟成雨TD10 分钟前
Spring AI 1.x 系列【57】动态工具发现:Tool Search Tool
java·人工智能·spring
苍何24 分钟前
一手实测 Claude Fable 5,手搓了个 Obsidian 的 Codex 插件
后端
zfoo-framework27 分钟前
[修改代码使用]codex官方app中使用中转(不需要cc-switch) 1.config.toml 2.sk方式登录
java
逍遥德1 小时前
MQTT教程详解-05.SpringBoot集成mqtt client 性能分析
java·spring boot·spring·mt
云烟成雨TD1 小时前
Spring AI 1.x 系列【54】Retry 机制分析
java·人工智能·spring
weixin_523185321 小时前
Collections.unmodifiableMap详解:真的不可修改吗?
java·linux·前端
点燃大海1 小时前
SpringAI构建智能体
java·spring boot·spring·springai智能体
xier_ran1 小时前
【infra之路】02_RadixAttention与KV_Cache管理
java·spring boot·spring
swipe1 小时前
做多轮对话 Agent,为什么我建议把短期记忆放到 Redis
后端·面试·llm
黑马师兄1 小时前
RAG混合检索深度解析:让AI真正找到你要的内容
java·人工智能·ai·agent·rag·ai-native