首页 > 其他 > 详细

freemakr小案例

时间:2019-05-12 17:22:04      阅读:204      评论:0      收藏:0      [点我收藏+]

最近接触了一个freemark最为静态化页面的项目,特地从网上搜索,写了一个小案例。

freemark静态化页面主要有两部分组成:模板和数据

数据通过流传到模板中,之后使用freemark特有的指令,将数据取出。

现在开始freemark小案例吧。

1:创建一个普通的java工程

技术分享图片

  三个红框分别代表的是2,3,4三个步骤

2:导入freemark.jar包

3:设置模板(注意模板的格式可以是任意,比如.html,.txt,.avi等等)


技术分享图片

使用${}来获取数据


 4:编写测试类

package cn.zkr.freemark;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

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

public class FreeMarkDemo {

private static final String path="E:/zixue/freemarkDemo/template";
public static void main(String[] args) throws IOException, TemplateException {

// 1.设置配置类
Configuration configuration = new Configuration();
//2. 设置模板所在的目录
configuration.setDirectoryForTemplateLoading(new File(path));
//3.设置字符集
configuration.setDefaultEncoding("utf-8");
//3.设置字符集
configuration.setDefaultEncoding("utf-8");
//4.加载模板
Template template = configuration.getTemplate("NewFile.html");
//5.创建数据模型
HashMap<String,String> map= new HashMap();
map.put("name1","小红");
map.put("name2","小明");
//6.创建Writer对象
FileWriter writer = new FileWriter(new File("D:/test.html"));
//7.输出数据模型到文件中
template.process(map,writer);
//8.关闭Writer对象
writer.close();

}


}

5:测试结果

技术分享图片

 

 

 

  

 

freemakr小案例

原文:https://www.cnblogs.com/hzw20131517/p/10852872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!