java使用freemarker生成静态html页面
- 格式:pdf
- 大小:60.40 KB
- 文档页数:2
java使⽤freemarker⽣成静态html页⾯
1. 模板⽂件static.html
描述:${description}
集合⼤⼩:${nameList?size}
迭代list集合:
<#list nameList as names>
这是第${names_index+1}个⼈,叫做:if判断:
<#if (names=="陈靖仇")>
他的武器是: ⼗五~~<#elseif (names=="宇⽂拓")> <#--注意这⾥没有返回⽽是在最后⾯-->
他的武器是: 轩辕剑~·<#else>
她的绝招是:蛊毒~~#if>
#list>
迭代map集合:
<#list weaponMap?keys as key>
key--->${key}
value----->${weaponMap[key]!("null")}
<#--
fremarker 不⽀持null, 可以⽤! 来代替为空的值。
其实也可以给⼀个默认值 value-----${weaponMap[key]?default("null")}
还可以 在输出前判断是否为null<#if weaponMap[key]??>#if>都可以
-->
#list>
2.⽣成代码:
package com.xijie.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;
/**
* @description
* @author ChangGui Pan
* @date 2018年7⽉19⽇ 上午11:38:53
*/
public class FreemarkerTest {
/**
* @description
* @author ChangGui Pan
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//创建⼀个合适的Configration对象
Configuration configuration = new Configuration();
// configuration.setDirectoryForTemplateLoading(new File("C:\\MyWork\\Workspace\\Xijie\\WebRoot\\html"));
configuration.setDirectoryForTemplateLoading(new File("./WebRoot/html"));
configuration.setObjectWrapper(new DefaultObjectWrapper());
configuration.setDefaultEncoding("UTF-8"); //这个⼀定要设置,不然在⽣成的页⾯中 会乱码
//获取或创建⼀个模版。
Template template = configuration.getTemplate("static.html");
Map
paramMap.put("description", "我正在学习使⽤Freemarker⽣成静态⽂件!");
List
nameList.add("陈靖仇");
nameList.add("⽟⼉");
nameList.add("宇⽂拓");
paramMap.put("nameList", nameList);
Map
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();
}
}
}