原理

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>
浙公网安备 33010602011771号