Thymeleaf(百里香叶)是一个适用于Web和独立环境的现代化服务器端Java模板引擎(如jsp)。
xmlns:th="http://www.thymeleaf.org"
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
官方文档:https://www.thymeleaf.org/documentation.html。
<table>
<thead>
<tr>
<th th:text="#{msgs.headers.name}">Name</th>
<th th:text="#{msgs.headers.price}">Price</th>
</tr>
</thead>
<tbody>
<tr th:each="prod: ${allProducts}">
<td th:text="${prod.name}">Oranges</td>
<td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
</tr>
</tbody>
</table>
可以在前端页面中填写占位符,而这些占位符的实际值则由后端进行提供,这样,我们就不用再像JSP那样前后端都写在一起了。
语法基础
前端
th:
能够拼接几乎所有的属性,一旦使用th:属性名称
,那么属性的值就可以通过后端提供了。
Thymeleaf还可以进行一些算术运算,几乎Java中的运算它都可以支持:
<div th:text="${value % 2}"></div>
同样的,它还支持三元运算:
<div th:text="${value % 2 == 0 ? 'yyds' : 'lbwnb'}"></div>
多个属性也可以通过+
进行拼接,就像Java中的字符串拼接一样,这里要注意一下,字符串不能直接写,要添加单引号:
<div th:text="${name}+' 我是文本 '+${value}"></div>
后端
控制流程
新建一个 Thymeleaf 页面
新建项目时需要勾选 Thymeleaf 依赖。在 resource 目录下新建一个 html 文件,并在html标签内部添加xmlns:th="http://www.thymeleaf.org"
引入Thymeleaf定义的标签属性:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${title}"></div>
</body>
</html>
对应的Servlet代码:
@WebServlet("/index")
public class HelloServlet extends HttpServlet {
TemplateEngine engine;
@Override
public void init() throws ServletException {
engine = new TemplateEngine();
ClassLoaderTemplateResolver r = new ClassLoaderTemplateResolver();
engine.setTemplateResolver(r);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Context context = new Context();
context.setVariable("title", "我是标题");
engine.process("test.html", context, resp.getWriter());
}
}
工具类
public class ThymeleafUtil {
private static final TemplateEngine engine;
static {
engine = new TemplateEngine();
ClassLoaderTemplateResolver r = new ClassLoaderTemplateResolver();
engine.setTemplateResolver(r);
}
public static TemplateEngine getEngine() {
return engine;
}
}