原理
public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
controller层会在classpath:/templates/下找到一.html结尾的html页面,controller返回的页面会自动拼接页面
1.导入依赖
<!--Thymeleaf--> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency>
2.使用参考文档Tutorial: Using Thymeleaf
参考
Simple expressions: Variable Expressions: ${...} Selection Variable Expressions: *{...} Message Expressions: #{...} Link URL Expressions: @{...} Fragment Expressions: ~{...} Literals Text literals: 'one text' , 'Another one!' ,… Number literals: 0 , 34 , 3.0 , 12.3 ,… Boolean literals: true , false Null literal: null Literal tokens: one , sometext , main ,… Text operations: String concatenation: + Literal substitutions: |The name is ${name}| Arithmetic operations: Binary operators: + , - , * , / , % Minus sign (unary operator): - Boolean operations: Binary operators: and , or Boolean negation (unary operator): ! , not Comparisons and equality: Comparators: > , < , >= , <= ( gt , lt , ge , le ) Equality operators: == , != ( eq , ne ) Conditional operators: If-then: (if) ? (then) If-then-else: (if) ? (then) : (else) Default: (value) ?: (defaultvalue)
1.导入头文件xmlns:th="http://www.thymeleaf.org"
2.controller层存数据
@RequestMapping("/test") public String test(Model model){ model.addAttribute("wang","王深圳"); return "test"; }
3.test.html取数据
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>test</h1> <h2 th:text="${wang}"></h2> </body> </html>
所有的html元素都可以被thymeleaf替换接管:th:元素名
遍历元素
<ul> <li th:text="${item}" th:each="item:${array}"></li> </ul>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!