跳到主要内容

Thymeleaf

参考资料

Thymeleaf 简介

Thymeleaf 是服务端模板技术,可用于替换 JSP。

配置 Thymeleaf

@WebServlet(name = "EmployeeViewServlet", value = "/employee.html", loadOnStartup = 0)
public class EmployeeViewServlet extends HttpServlet {

private TemplateEngine templateEngine;

@Override
public void init() throws ServletException {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(getServletContext());
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".html");
templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
List<Employee> list = GenericQuery.getList(Employee.class, "select * from employees");
req.setAttribute("employees", list);
} catch (SQLException e) {
e.printStackTrace();
req.setAttribute("err", e.getMessage());
}
templateEngine.process("employee", new WebContext(req, resp, getServletContext()), resp.getWriter());
}

}

约束

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

</body>
</html>