首先看一下目录结构:
然后从pom配置开始:
第一步:引用:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
截图如下:
第二步:配置properties
# Enable template caching.
spring.thymeleaf.cache=false
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value.
spring.thymeleaf.servlet.content-type=text/html
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true
# Template encoding.
spring.thymeleaf.encoding=UTF-8
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names=
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html
更多配置可以访问:org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties类查看。
第三步:页面。
众所周知,thymeleaf 的页面是html,而非jsp。Springboot也建议如此使用。
页面默认存放路径为:\src\main\resources\templates
tab.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1 th:text="${name}">Hello World</h1>
</body>
</html>
第四步:后台跳转
依然沿用了Spring的跳转设置,在参数上添加了ModelMap用于数据的传输。代码如下:
ThymeleafController.java
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ThymeleafController {
@RequestMapping("/")
public String index(ModelMap param) {
param.addAttribute("name", "I`m Iceter!");
// return模板文件的名称,对应src/main/resources/templates/tab.html
return "tab";
}
}
至此,配置及页面跳转已经完成。启动后,可以通过
http://localhost:8080/tab.html
进行访问。正常访问结果如下:
附件:
在thymeleaf 的使用过程中,我们经常会用到代码提示,thymeleaf 的页面编辑中也有自动提示。如下:
自动提示插件安装地址:
https://www.thymeleaf.org/eclipse-plugin-update-site/
下载安装之后即可使用。
源代码下载地址:
https://download.csdn.net/download/u011561335/10413152
参考博文:
https://blog.csdn.net/winter_chen001/article/details/78330142
https://blog.csdn.net/u012706811/article/details/52185345