页面静态化
FreeMarker是一种基于模板的、用来生成输出文本的通用工具,可以通过我们定制的模板生成自己的Html页面。
FreeMarker是通过 freemarker.template.Configuration
这个对象对模板进行加载的(它也处理创建和缓存预解析模板的工作),然后我们通过getTemplate
方法获得想要的模板。但是freemarker.template.Configuration
在整个应用必须保证唯一实例。
示例:
编写模板文件
<!doctype html>
<html lang="en">
<head>
<title>${webName}</title>
</head>
<body>
<h2>${newsTitle}</h2><br>
<div> ${content} </div>
</body>
</html>
编写Servlet:
@WebServlet("/createPage")
public class CreatePageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 实例化模板配置对象
Configuration configuration = new Configuration(Configuration.VERSION_2_3_0); // 旧版的Configuration构造方法不需要传入参数
// 设置加载模板的上下文和模板存放的路径
configuration.setServletContextForTemplateLoading(getServletContext(), "/template");
// 设置编码
configuration.setDefaultEncoding("UTF-8");
// 加载模板文件,获取模板对象
Template template = configuration.getTemplate("page.ftl");
// 设置生成的静态文件路径
File file = new File("D:/tmp/aaa.html");
FileWriter writer = new FileWriter(file);
// 添加变量
Map<String, Object> map = new HashMap<>(2);
map.put("webName", "测试页面");
map.put("newsTitle", "这是新闻标题");
map.put("content", "hello world");
try {
template.process(map, writer);
System.out.println("静态html创建成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
writer.flush();
writer.close();
}
}
}