一、首先明白freemarker的几个概念
1、 数据模型 用于封装数据
2、模板模型 也就是FTL,在模板模型中可以展示数据模型
二、freemarker的工作原理。是将数据模型封装在map中,将数据在FTL页面中进行展示。
package com.joeho.freemarker;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreemarkerUtil {
//获取FTL模板
public Template getTemplate(String name){
Configuration cft = new Configuration();
cft.setClassForTemplateLoading(this.getClass(), "/ftl");
try {
return cft.getTemplate(name);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//将模板打印到控制台输出
public void print(String name,Map<String,Object> rootMap){
Template temp = this.getTemplate(name);
try {
temp.process(rootMap, new PrintWriter(System.out));
} catch (Exception e) {
}
}
//将模板输出成静态html
public void print2File(String name,Map<String,Object> rootMap,String file){
Template temp = this.getTemplate(name);
FileWriter outer=null;
try {
outer=new FileWriter(new File("D:\\Develop\\eclipseSpaces\\template\\"+file));
temp.process(rootMap, outer);
} catch (Exception e) {e.printStackTrace();}
finally{
if(outer!=null){
try {
outer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
三、模板ftl文件 "datatype.ftl",
<!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>
${username}
<#--定义变量,四种基本数据类型 数字、字符串、布尔值、日期-->
<#assign username="张三" />
${username}
<#assign age=22 /></br>
${age}
<#assign isweman=false /></br><#--布尔值不能直接输出,需要转化成string-->
${isweman?string}
${now?string("yyyy-MM-dd HH:mm:ss")}
<#--使用插值的方式连接字符串-->
${"hello${username}"}
<#--使用日期类型-->
<#assign birthday="1980-02-26"?date("yyyy-MM-dd") />
${birthday}
<#--转义字符-->
${"<br>"!html}
<#--内嵌函数-->
${1.4?int}
<#--序列-->
<#assign nums=[1,2,3,4] />
<#assign nums=1..20>
<#assign nums=nums[1..5] />
<#list nums as num>
${num}
</#list><br>
<#--哈希-->
<#assign maps={"1":"xupeng","2":"zhangsan"}>
<#assign keys=maps?keys>
${maps["1"]}
<#list keys as key>
${key}====${maps[key]}
</#list>
</body>
</html>
四、测试类
package com.joeho.freemarker;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.joeho.modle.Group;
import com.joeho.modle.User;
public class FreemarkerTest {
FreemarkerUtil ftl = new FreemarkerUtil();
Map<String,Object> rootMap = new HashMap<String, Object>();
@Before
public void setUp(){
ftl = new FreemarkerUtil();
rootMap = new HashMap<String, Object>();
}
@Test
public void testDatatype(){
rootMap.put("username", "1111");
rootMap.put("now", new Date());
ftl.print("datatype.ftl", rootMap);
}
}