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

效果图展示

项目目录结构

相关推荐
星辰_mya16 小时前
三级缓存破局:Spring 如何优雅解决循环依赖?
java·spring·缓存·面试
BUG胡汉三16 小时前
Java内网代理访问HTTPS接口SSL证书不匹配
java·https·ssl
洛邙16 小时前
互联网大厂Java求职面试实录:Spring Boot与微服务实战解析
java·spring boot·缓存·微服务·面试·分布式事务·电商
java1234_小锋16 小时前
Java高频面试题:Spring框架中的单例bean是线程安全的吗?
java·数据库·spring
代码探秘者16 小时前
【大模型应用】5.深入理解向量数据库
java·数据库·后端·python·spring·面试
小王不爱笑13216 小时前
Java 代理模式与 AOP 底层
java·开发语言·代理模式
weixin_4041576816 小时前
Java高级面试与工程实践问题集(二)
java·开发语言·面试
渔民小镇16 小时前
不止 request/response —— ionet 的 4 种通信模型选型指南
java·服务器·游戏
逍遥德16 小时前
Postgresql explain执行计划详解
数据库·后端·sql·postgresql·数据分析
金蕊泛流霞16 小时前
Spring AI Alibaba笔记
java·笔记·spring