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

效果图展示

项目目录结构

相关推荐
Python私教1 分钟前
使用 SQLAlchemy 连接数据库:从基础到最佳实践
后端
通域4 分钟前
解决启动IDEA后CPU 及内存占用过高配置调整
java·ide·intellij-idea
一袋米扛几楼9820 分钟前
【软件安全】C语言特性 (C Language Characteristics)
java·c语言·安全
will_we29 分钟前
Spring Boot4先行篇:第一篇 Spring Boot 创建 Docker 镜像
spring boot
Q_Q19632884751 小时前
python+django/flask基于协同过滤算法的理财产品推荐系统
spring boot·python·django·flask·node.js·php
m0_748248021 小时前
《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
java·开发语言·c++·算法
aloha_7891 小时前
测试开发工程师面经准备(sxf)
java·python·leetcode·压力测试
码起来呗1 小时前
基于Spring Boot的乡村拼车小程序的设计与实现-项目分享
spring boot·后端·小程序
我命由我123452 小时前
Java 并发编程 - Delay(Delayed 概述、Delayed 实现、Delayed 使用、Delay 缓存实现、Delayed 延迟获取数据实现)
java·开发语言·后端·缓存·java-ee·intellij-idea·intellij idea
北城以北88882 小时前
SSM--MyBatis框架之缓存
java·缓存·intellij-idea·mybatis