FreeMarker是一个用Java语言编写的模板引擎,它基于模板输出文本。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
目前企业中:主要用Freemarker做静态页面生成。
原理:
生成代码:
public class MyGenHtml {
public static void main(String[] args) throws Exception {
//创建Configuration对象,构造入参为freemarker的版本号,
//直接通过Configuration.getVersion()获取freemarker版本号
Configuration config = new Configuration(Configuration.getVersion());
//设置模板文件所在的路径 工程下的template文件
config.setDirectoryForTemplateLoading(new File("template"));
//设置模板文件使用的字符集。一般就是utf-8.
config.setDefaultEncoding("UTF-8");
//加载一个模板,创建一个模板对象。
Template template = config.getTemplate("hello.htm");
//创建一个模板使用的数据集
HashMap<String,Object> model = new HashMap();
model.put("hello", "hello world 你好世界");
Person p1 = new Person(1001, "张三");
model.put("person",p1);
List<Person> list = new ArrayList<Person>();
list.add(new Person(1001, "zhaoyun"));
list.add(new Person(1002, "关羽"));
list.add(new Person(1003, "张飞"));
model.put("list", list);
HashMap<String, Object> peple = new HashMap<String, Object>();
peple.put("m1", new Person(1001, "西斯"));
peple.put("m2", new Person(1001, "貂蝉"));
peple.put("m3", new Person(1001, "王战军"));
model.put("map", peple);
model.put("date", new Date());
// model.put("test", "1111");
//创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
FileWriter writer = new FileWriter(new File("result","result.htlm"));
//调用模板对象的process方法输出文件
template.process(model,writer);
//关闭流。
writer.close();
}
}
模板: 模板名称可以任意,一般以 ftl 结尾
//map中通过key获取值
${hello}
//获取POJO
${person.id?c} ${person.name}
//list
//其中:list as person中的
//list 为模型设置中的key
//person:为集合中的元素的名称 (可以任意)
<#list list as person>
${(person_index+1)?c} ${person.id?c} ${person.name}
</#list>
//map map?keys 获取map中所有的key
<#list map?keys as key>
${map[key].id?c} ${map[key].name}
</#list>
//if
<#list list as people>
<#if people_index%2=0>
这是奇数行 ${people_index+1}
<#else>
这是偶数行 ${people_index+1}
</#if>
${people.id} ${people.name}
</#list>
//date
${date?date} ${date?string("yyyy-MM-dd hh:mm:ss")}
//test null值测试
${test!"默认显示"}
//最后
<#include "template.htm"/>
与Spring整合:
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
@Controller
public class HtmGenController {
@Autowired
private FreeMarkerConfigurer freemarkerConfig;
@RequestMapping("/htmGen")
@ResponseBody
public String HtmGen() throws Exception{
Configuration configuration = freemarkerConfig.getConfiguration();
//获取模板
Template template = configuration.getTemplate("template.ftl");
//添加模板数据
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("springtestkey", "freeMark 与 spring 整合");
//创建FileWrite
Writer write = new FileWriter(new File("F:/test.html"));
//通过模板的 process输出
template.process(map, write);
//关闭流
write.close();
return "OK";
}
}