页面静态化

FreeMarker是一种基于模板的、用来生成输出文本的通用工具,可以通过我们定制的模板生成自己的Html页面。

FreeMarker是通过 freemarker.template.Configuration这个对象对模板进行加载的(它也处理创建和缓存预解析模板的工作),然后我们通过getTemplate方法获得想要的模板。但是freemarker.template.Configuration在整个应用必须保证唯一实例。

示例:

编写模板文件

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <title>${webName}</title>
  5. </head>
  6. <body>
  7. <h2>${newsTitle}</h2><br>
  8. <div> ${content} </div>
  9. </body>
  10. </html>

编写Servlet:

  1. @WebServlet("/createPage")
  2. public class CreatePageServlet extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. // 实例化模板配置对象
  6. Configuration configuration = new Configuration(Configuration.VERSION_2_3_0); // 旧版的Configuration构造方法不需要传入参数
  7. // 设置加载模板的上下文和模板存放的路径
  8. configuration.setServletContextForTemplateLoading(getServletContext(), "/template");
  9. // 设置编码
  10. configuration.setDefaultEncoding("UTF-8");
  11. // 加载模板文件,获取模板对象
  12. Template template = configuration.getTemplate("page.ftl");
  13. // 设置生成的静态文件路径
  14. File file = new File("D:/tmp/aaa.html");
  15. FileWriter writer = new FileWriter(file);
  16. // 添加变量
  17. Map<String, Object> map = new HashMap<>(2);
  18. map.put("webName", "测试页面");
  19. map.put("newsTitle", "这是新闻标题");
  20. map.put("content", "hello world");
  21. try {
  22. template.process(map, writer);
  23. System.out.println("静态html创建成功");
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. } finally {
  27. writer.flush();
  28. writer.close();
  29. }
  30. }
  31. }