<!-- 引入thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency>
进入ThymeleafAutoConfiguration:
@Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(ThymeleafProperties.class) @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class }) @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class }) public class ThymeleafAutoConfiguration { ...
进入ThymeleafProperties.class查看:
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; //默认前缀 public static final String DEFAULT_SUFFIX = ".html"; //默认后缀 ...
从源码得知Thymeleaf的存放路径为:classpath:/templates/ ;且文件必须以".html"为后缀。
3.1、加入首标签
<html xmlns:th="http://www.thymeleaf.org">
3.2、运用th:输出
先在controller层赋值:
@RequestMapping("/welcome") public String welcome(Map<String,Object> map) { map.put("welcome", "XXX的thymeleaf欢迎你"); return "index"; }
再在HTML中引用:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <p th:text="${welcome}">Welcome to our grocery store!</p> //th:+XX 可以实现替换 XX 中值的功能 </body> </html>
访问控制器则不会显示p标签内的内容,而是显示赋值的内容。
th:可替代的属性:
th:text 获取文本值(转义) th:utext 获取文本值(不转义)
3.3、迭代实例
public void process(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final ITemplateEngine templateEngine)throws Exception {
ProductService productService = new ProductService();
List<Product> allProducts = productService.findAll();
WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
ctx.setVariable("prods", allProducts);
templateEngine.process("product/list", ctx, response.getWriter());
}
<html xmlns:th="http://www.thymeleaf.org"> <head> <title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
</head> <body> <h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
<p> <a href="../home.html" th:href="@{/}">Return to home</a> </p> </body> </html>
更多使用参考博文:https://www.cnblogs.com/msi-chen/p/10974009.html
原文:https://www.cnblogs.com/709539062rao/p/12616336.html