导入相关Jar包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.22</version>
</dependency>
测试类
public class FreemarkerTest {
@Test
public void testFreeMarker() throws IOException, TemplateException {
Configuration configuration = new Configuration(Configuration.getVersion());
configuration.setDirectoryForTemplateLoading(new File("E:\\workspace\\logistics\\src\\main\\webapp\\WEB-INF\\ftl"));
configuration.setDefaultEncoding("utf-8");
Template template = configuration.getTemplate("first.ftl");
Map root = new HashMap();
root.put("hello", "hello,freemarker");
root.put("user", new User("jack",23));
root.put("strs",new String[]{"a","b","c"});
List<User> users=new ArrayList<User>();
users.add(new User("a1",21));
users.add(new User("a2",22));
users.add(new User("a3",23));
root.put("users",users);
root.put("date",new Date());
Writer out = new FileWriter(new File("E:\\workspace\\logistics\\src\\main\\webapp\\WEB-INF\\ftl\\hell.html"));
template.process(root, out);
out.flush();
out.close();
}
}
模板
<html>
<head>
<meta charset="utf-8">
<title>freemarker</title>
</head>
<body>
<h1>取简单数据</h1>
<h2>使用el表达式</h2>
${hello}
<h2>取包装数据类型</h2>
${user.name}
${user.age}
<h2>遍历集合和数组</h2>
<#list strs as str>
${str_index}
${str}
</#list>
<#list users as user>
${user.name}/${user.age}
</#list>
<h2>判断条件</h2>
<#if 1==2>
1==2
<#else>
1!=2
</#if>
<h2>格式化日期</h2>
${date?date}
${date?datetime}
${date?time}
${date?string("yyyy-MM-dd HH:mm:ss")}
<h2>null处理</h2>
<P>在jsp中会自动忽略而freemarker不会</P>
${asdfs!"默认值"}
${asd123fs!""}
<#if date ??>
${date?string("yyyy-MM-dd HH:mm:ss")}
<#else>
日期不存在
</#if>
<h2>include</h2>
<#include "second.ftl"/>
</body>
</html>