当前位置: 首页 > news >正文

springboot 下的Thymeleaf 前端渲染引擎

Thymeleaf 是一种现代化的服务器端 Java 模板引擎,常用于 Spring Boot 项目中,支持动态页面渲染和前后端分离。

1. 创建 Spring Boot 项目

  1. 使用 IDE(如 IntelliJ IDEA)创建一个 Spring Boot 项目。

  2. 在项目创建时,选择以下依赖: Spring Web:用于构建 Web 应用。 Thymeleaf:模板引擎支持。

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
</dependencies>

2. 配置 Thymeleaf

在 application.properties 或 application.yml 中添加以下配置:

spring.thymeleaf.cache=false # 禁用缓存(开发时使用)
spring.thymeleaf.prefix=classpath:/templates/ # 模板文件路径
spring.thymeleaf.suffix=.html # 模板文件后缀
spring.thymeleaf.encoding=UTF-8 # 文件编码

3. 编写 Controller

创建一个控制器类,用于处理请求并传递数据到模板:

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {@GetMapping("/hello")public String hello(Model model) {model.addAttribute("message", "欢迎使用 Thymeleaf!");return "hello"; // 对应 templates/hello.html
   }
}

4. 创建 Thymeleaf 模板

在 src/main/resources/templates 目录下创建 hello.html 文件:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Thymeleaf 示例</title>
</head>
<body><h1 th:text="${message}">默认消息</h1>
</body>
</html>

5. 启动项目并测试

  1. 启动 Spring Boot 项目。

  2. 在浏览器中访问 http://localhost:8080/hello,页面将显示传递的动态数据。

 

Thymeleaf 

  • 动静分离:Thymeleaf 支持直接打开 HTML 文件查看静态效果,方便前端开发。

  • 扩展性:可自定义方言和标签,满足复杂需求。

  • 性能优化:生产环境建议开启模板缓存(spring.thymeleaf.cache=true)。

 

http://www.gsyq.cn/news/41703.html

相关文章:

  • 2025年泉州苹果售后维修点推荐:主流门店列表与选择方案
  • 利用keil +RASC给瑞萨RA8D1编译烧写软件
  • Gitee:中国DevSecOps实践的标杆与未来
  • MyEMS:智能化能源管理的创新实践者
  • 2025年抖音SEO排名推荐:市场报告揭示的头部解决方案
  • 2025年精密精轧管生产厂家权威推荐榜单:不锈钢管精轧管/冷拔管精轧管/精轧焊管源头厂家精选
  • 还在担心文件泄露?这个浏览器里的格式转换工具,给了另一种答案
  • 2025年11月效果图公司推荐榜:权威评测五强排名与横向对比
  • psql -U PostgreSQL端命令
  • Linux V4L2框架详解:Camera软件架构与驱动达成
  • 简单接口并发测试
  • 2025 年白炭黑生产厂家最新推荐排行榜:涵盖微珠 / 疏水 / 气相法 / 沉淀法等多类型产品,权威测评选出优质企业供下游参考二氧化硅/胶粉用白炭黑公司推荐
  • 2025年11月中国GEO平台推荐排行榜:AI搜索优化技术全面解析
  • 【Linux dbus】问题解决 Failed to connect to socket /run/user/1000/bus: No such file or directory
  • Windows系统真随机数生成器实现
  • 2025年11月沈阳代理记账公司排行榜:专业顾问的深度推荐
  • Chronic disease
  • 11.6 1.基础HTTPGET接口请求测试
  • 2025年11月学习机品牌推荐榜:清北双师与AI精准学排行盘点
  • Linux - 压缩解压篇
  • P2416 泡芙 题解
  • post表单提交接口测试
  • AI元人文构想:人机共生智慧文明治理新范式整理报告
  • 2025年湖南专利申请公司权威推荐榜单:期刊论文公司/专著合著出版公司/重点课题申报服务机构精选
  • 基础HTTP GET接口请求测试
  • HTTPPOST表单提交接口测试
  • 能变声的录放音语音芯片WT2003Hx
  • 2025年知名的多品种小批量零件机械加工TOP实力厂家推荐榜
  • 2025年智能铝合金门窗定制厂家权威推荐榜单:智能门窗控制系统/高性能系统门窗/高性能节能门窗源头厂家精选
  • 2025年铝合金锯片厂家权威推荐榜单:超薄铝用锯片/断桥铝锯片/金刚石锯片源头厂家精选