FreeMarker 之快速入门Demo

  • 开发环境
  • freemaker版本2.3.23
  • Eclipse Mars.2

创建maven的jar工程

在eclipse中new 一个maven project,填入如下的信息,创建工程,工程起名为freemakerdemo

导入依赖

在pom.xml中引入如下的依赖

     <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>

创建模板文件

在resource目录下,创建test.ftl文件

test.ftl文件中写入如下的内容

<html>
<head>
    <meta charset="utf-8">
    <title>Freemarker入门小DEMO </title>
</head>
<body>
<#--我只是一个注释,我不会有任何输出  -->
${name},你好。${message}
</body>
</html>

新建测试类生成html文件

创建如下图的测试类

测试类中的代码如下

package com.thc.test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import freemarker.template.Configuration;
import freemarker.template.Template;
@SuppressWarnings("all")
public class Test01 {
    public static void main(String[] args) throws Exception {
        // 1.设置配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        //2. 设置模板所在的目录
        configuration.setDirectoryForTemplateLoading(
                new File("D:/develop/eclipse_workspace/eclipsePinyougou/freemakerdemo/src/main/resources/"));
        //3.设置字符集
        configuration.setDefaultEncoding("utf-8");
        //4.加载模板
        Template template = configuration.getTemplate("test.ftl");
        //5.创建数据模型
        HashMap map = new HashMap();
        map.put("name""周杰伦");
        map.put("message""我是你的老歌迷了");
        //6.创建Writer对象
        FileWriter writer = new FileWriter(new File("D:/freemaker/test.html"));
        //7.输出数据模型到文件中
        template.process(map, writer);
        //8.关闭Writer对象
        writer.close(); 
    }
}

运行该main方法后,在D:\freemaker目录下,生成了html文件

打开页面后显示如下的内容

可以看到在java代码中,map中put的name和message替代了模板文件中的内容.

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/80933851