开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第11天,点击查看活动详情
模板引擎技术介绍
模板引擎(这里特指用于Web开发的模板引擎)是为了使用户看到的页面与业务数据分离而产生的一种模板技术。它可以生成特定格式的文档,用于网站的模板引擎就会生产出标准的HTML静态页面内容。
使用模板引擎技术可以动态加载数据。在开发过程中,开发人员需要制作出模板引擎文件(不同的模板引擎技术的规范不同),并在控制器中将模板需要的数据组装好,然后将二者都交给模板引擎,模板引擎会根据数据和模板表达式语法解析并填充其到指定的位置进行页面渲染,最终生成HTML内容响应给客户端。
使用Thymeleaf模板引擎
Thymeleaf(百里香叶)是一个适用于Web和独立环境的现代化服务器端Java模板引擎,官方文档:www.thymeleaf.org/
<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那样前后端都写在一起了。 那么我们来创建一个例子感受一下
首先编写一个前端页面,名称为test.html,注意,是放在resource目录下,在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作为默认页面:
resp.setCharacterEncoding("UTF-8");防止乱码,加上这一句代码
@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", "我是标题");
resp.setCharacterEncoding("UTF-8");
engine.process("test.html", context, resp.getWriter());
}
}
访问得到
我们发现,浏览器得到的页面,就是已经经过模板引擎解析好的页面,而我们的代码依然是后端处理数据,前端展示数据,因此使用Thymeleaf就能够使得当前Web应用程序的前后端划分更加清晰。