springboot模板引擎Thymeleaf
Thymeleaf
1.导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.查看源码
thymeleaf的html都写在resources/templates下
3.测试前端代码
注意添加命名空间
xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>测试页面</h1> <div th:text="${msg}"></div> </body> </html>
4.后台请求代码
package com.chen.boot.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { @RequestMapping("/test") public String test(Model model){ model.addAttribute("msg","success"); return "test"; } }
5.抽取公共部分
写一个commom.html
将网页中公共的引入css 引js 还有别的公共代码写出来
并在公共部分 使用 th:fragment="commonheader" 或者用id选择器 将公共部分声明
当我们使用公共部分的时候。使用th:insert th:peplace th:include (这三者是不一样的!!)
使用 th:fragment="commonheader" 的我们直接 th:include="公共页面名字 :: commonheader" 即可
使用id选则器的话 我们要加# th:include="公共页面名字 :: #commonleftmeun"
7.遍历后台数据
@GetMapping("/dynamic_table") public String dynamic_table(Model model){ //新建几个对象放到列表里面,传给前台,前台去遍历到表格中 List<User> users = Arrays.asList(new User("chen", "123"), new User("chen2", "456"), new User("chen3", "789")); model.addAttribute("userList",users); return "table/dynamic_table"; }
遍历使用 th:each="自定义参数:${列表名字}" 这个例子里面的stats是Thymeleaf的公共部分,表示遍历列表的状态
分类:
SpringBoot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现