用Freemarker模板輸出文件
建立Freemarker模板
freemarker.ftl
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome!</title>
</head>
<body>
<#if username == "李雨翔">
<h1>
Welcome 大帥哥
</h1>
<#else>
<h1>
Welcome ${username}
</h1>
</#if>
<ul>
<#list goodsList as goods>
<li><span>Good's name: </span><a href="${goods.url}">${goods.name}</a></li>
</#list>
</ul>
</body>
</html>
輸出freemarker的java程序
Goods.java
package com.lyx.freemaker;
public class Goods {
private String name;
private String url;
public Goods() {
}
public Goods(String name, String url) {
super();
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Freemarker.java
package com.lyx.freemaker;
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.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
public class Freemaker {
public static void main(String[] args) throws IOException, TemplateException {
Version version = new Version("2.3.23");
Configuration cfg = new Configuration(version);
cfg.setDirectoryForTemplateLoading(new File("D:\\eclipse-workspace\\freemarker\\src\\main\\java"));
Template template = cfg.getTemplate("freemaker.ftl","utf-8");
template.setClassicCompatible(true);
Writer writer = new OutputStreamWriter(new FileOutputStream("D:\\BaiduNetdiskDownload\\freemaker.html"), "utf-8");
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("username", "李雨翔");
Goods goods = new Goods("Head first", "https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.1.7e43e67a2zjSoD&id=526232391362&areaId=510700&user_id=327369967&cat_id=2&is_b=1&rn=8bf7381d3a156942e22689f842dba043");
Goods goods1 = new Goods("PHP", "https://detail.tmall.com/item.htm?spm=a220o.1000855.0.0.39c8b885YVHho2&abtest=_AB-LR67-PR67&pvid=969ca72c-1992-469f-b912-bdcf5f571786&pos=1&abbucket=_AB-M67_B14&acm=03067.1003.1.1977615&id=526497761968&scm=1007.12776.82642.100200300000000");
Goods goods2 = new Goods("java入門", "https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.1.16a9dc7aIyxLbf&id=559132036057&skuId=3649437991258&areaId=510700&user_id=2646031546&cat_id=2&is_b=1&rn=6ddf4ec2b2ea8f07c0f689ddba0fdb92");
List<Goods> goodsList= new ArrayList<>();
goodsList.add(goods);
goodsList.add(goods1);
goodsList.add(goods2);
dataModel.put("goodsList", goodsList);
template.process(dataModel, writer);
writer.close();
}
}