<#include "include.html"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
描述:${description}
<br/>
集合大小:${nameList?size}
<br/>
迭代list集合:
<br/>
<#list nameList as names>
这是第${names_index+1}个人,叫做:<label style="color:red">${names}</label>
if判断:
<br/>
<#if (names=="陈靖仇")>
他的武器是: 十五~~
<#elseif (names=="宇文拓")> <#--注意这里没有返回而是在最后面-->
他的武器是: 轩辕剑~·
<#else>
她的绝招是:蛊毒~~
</#if>
<br/>
</#list>
迭代map集合:
<br/>
<#list weaponMap?keys as key>
key--->${key}<br/>
value----->${weaponMap[key]!("null")}
<#--
fremarker 不支持null, 可以用! 来代替为空的值。
其实也可以给一个默认值
value-----${weaponMap[key]?default("null")}
还可以 在输出前判断是否为null
<#if weaponMap[key]??></#if>都可以
-->
<br/>
</#list>
include导入文件:
<br/>
<#include "include.html"/>
</body>
</html>
package com.chenghui.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class CreateHtml {
public static void main(String[] args) {
try {
//创建一个合适的Configration对象
Configuration configuration = new Configuration();
configuration.setDirectoryForTemplateLoading(new File("D:\\project\\webProject\\WebContent\\WEB-INF\\template"));
configuration.setObjectWrapper(new DefaultObjectWrapper());
configuration.setDefaultEncoding("UTF-8"); //这个一定要设置,不然在生成的页面中 会乱码
//获取或创建一个模版。
Template template = configuration.getTemplate("static.html");
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("description", "我正在学习使用Freemarker生成静态文件!");
List<String> nameList = new ArrayList<String>();
nameList.add("陈靖仇");
nameList.add("玉儿");
nameList.add("宇文拓");
paramMap.put("nameList", nameList);
Map<String, Object> weaponMap = new HashMap<String, Object>();
weaponMap.put("first", "轩辕剑");
weaponMap.put("second", "崆峒印");
weaponMap.put("third", "女娲石");
weaponMap.put("fourth", "神农鼎");
weaponMap.put("fifth", "伏羲琴");
weaponMap.put("sixth", "昆仑镜");
weaponMap.put("seventh", null);
paramMap.put("weaponMap", weaponMap);
Writer writer = new OutputStreamWriter(new FileOutputStream("success.html"),"UTF-8");
template.process(paramMap, writer);
System.out.println("恭喜,生成成功~~");
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}