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

效果图展示

项目目录结构

相关推荐
clk66071 小时前
SSM 框架核心知识详解(Spring + SpringMVC + MyBatis)
java·spring·mybatis
JohnYan3 小时前
Bun技术评估 - 04 HTTP Client
javascript·后端·bun
shangjg33 小时前
Kafka 的 ISR 机制深度解析:保障数据可靠性的核心防线
java·后端·kafka
青莳吖4 小时前
使用 SseEmitter 实现 Spring Boot 后端的流式传输和前端的数据接收
前端·spring boot·后端
我的golang之路果然有问题4 小时前
ElasticSearch+Gin+Gorm简单示例
大数据·开发语言·后端·elasticsearch·搜索引擎·golang·gin
Alan3164 小时前
Qt 中,设置事件过滤器(Event Filter)的方式
java·开发语言·数据库
小鹭同学_5 小时前
Java基础 Day28 完结篇
java·开发语言·log4j
椰椰椰耶6 小时前
[网页五子棋][匹配模块]实现胜负判定,处理玩家掉线
java·开发语言·spring boot·websocket·spring
on the way 1236 小时前
结构性设计模式之Flyweight(享元)
java·设计模式·享元模式
mldong6 小时前
我的全栈工程师之路:全栈学习路线分享
前端·后端