Freemarker页面静态化技术

简介: Freemarker是一款模板引擎,即一种基于模板,用来生成输出文本(任何来自于HTML格式的文本用来自动生成源代码)的通用工具;
在访问新闻、活动、商品详情页面时, 路径可以是 xx【id】.html, 服务器端根据请
求 id, 动态生成 html 网页,下次访问数据时,无需再查询数据,直接将 html 静态页面返
回 ,这么做可以减少数据库交互,提高查询性能,将动态数据访问,缓存为一个静态 html 页面,提高查询效率;
入门使用:
1.安装 freemarker eclipse 编辑插件
将 “freemarker_eclipseplugin” 复制 eclipse 的 dropins 文件夹 ,重启开发工具
2.编辑 freemarker 的模板文件
通常模板文件 放在 WEB-INF 下 或者 classes 下(模板一般后缀名为ftl)
这里写图片描述
这里写图片描述
3.编写测试代码:

package cn.itcast.bos.dao.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerTest {
    @Test
    public void testOutput() throws IOException, TemplateException {
        // 配置对象, 配置模板位置
        Configuration configuration = new Configuration(
                Configuration.VERSION_2_3_22);
        configuration.setDirectoryForTemplateLoading(new File(
                "src/main/webapp/WEB-INF/templates"));

        // 获取模板对象
        Template template = configuration.getTemplate("hello.ftl");

        // 动态数据对象
        Map<String, Object> paramterMap = new HashMap<String, Object>();
        paramterMap.put("title", "这里是demo1");
        paramterMap.put("msg", "你好,这是第一个Freemarker案例!");

        // 合并输出
        template.process(paramterMap, new PrintWriter(System.out));
    }
}

4.运行测试类结果:

<html>
<head>这里是demo1</head>
<body>你好,这是第一个Freemarker案例!</body>
</html>

笔记整理:

  1. 模板: 可以是任意文件名。表达式 :${name}.
  2. 代码:固定的步骤
    1. 获取配置(设置freemarker的版本,设置模板所在的目录)
    2. 获取模板对象。(根据模板文件的名称)
    3. 设置模板需要的参数。(Map)
    4. 调用模板的方法,通过输出流合并参数,并输出文件
  3. 注意:
    1. 模板存在的变量,一定要在map中复制,除非通过!提供默认值。
    2. 日期类型的变量,输出的时候,要提供格式: ${mydate?string(“yyyy-MM-dd HH:mm:ss”)}

猜你喜欢

转载自blog.csdn.net/caiyibing1992/article/details/82387228