1、引入包,我引入的是freemarker-2.3.18.jar
2、编写ftl模版文件,模版文件也就是你的动态页面,将比如JSTL标签替换成freemarker的标签,例如:
<c:forEach items="${articleList}" var="list">
${list.title}
</c:forEach>
使用freemarker后,要改为:
<#list articleList as list>
${list.title}
</#list>
注意一点,如果你的数据为数字格式,且长度超过三位,比如1000,freemarker会将其变为1,000,要使用?c将符号清除,
如:${number?c}
freemarker接收的参数是Map<String,Object>类型的。
3、创建生成HTML的工具类:
public class CreateHtmlUtils {
/**
* 通过freemarker生成静态HTML页面
* @param ftlName 模版名称
* @param targetFileName 模版生成后的文件名
* @param map freemarker生成的数据都存储在MAP中,
* @创建时间:2017年10月22日21:41:06
*/
public static void createHtml(String templateName,String targetFileName,Map<String, Object> map) throws Exception{
//创建fm的配置
Configuration config = new Configuration();
//指定默认编码格式
config.setDefaultEncoding("UTF-8");
//设置模版文件的路径
config.setClassForTemplateLoading(CreateHtmlUtils.class, "/com/test/shop/ftl");
//获得模版包
Template template = config.getTemplate(templateName);
//从参数文件中获取指定输出路径 ,路径示例:C:/Workspace/shop-test/src/main/webapp/html
String path = PropUtils.readKey("create_html_path");
//定义输出流,注意必须指定编码
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path+"/"+targetFileName)),"UTF-8"));
//生成模版
template.process(map, writer);
}
}
5、创建ftl模版文件 test.ftl
<html>
<body>
<h2>${hello}</h2>
</body>
</html>
6、创建测试类,生成html文件
Hello World!
@Test
public void testCreateHtml() throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
map.put("hello", "Hello World!");
CreateHtmlUtils.createHtml("test.ftl","test.html" , map);
}
7、执行结果:
创建成功,打开看一下,是不是我们输入的内容: