1. 什么是freemarker
FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
2.Freemarker的使用方法
public void testFreemarker() throws Exception{
//第一步:把freemarker的jar包添加到工程中
//第二步:freemarker的运行不依赖web容器,可以在java工程中运行。创建一个测试方法进行测试。
//第三步:创建一个Configration对象
Configuration configuration = new Configuration(Configuration.getVersion());
//第四步:告诉config对象模板文件存放的路径。
configuration.setDirectoryForTemplateLoading(new File("D:/template"));
//第五步:设置config的默认字符集。一般是utf-8
configuration.setDefaultEncoding("utf-8");
//第六步:从config对象中获得模板对象。需要制定一个模板文件的名字。
Template template = configuration.getTemplate("second.ftl");
//第七步:创建模板需要的数据集。可以是一个map对象也可以是一个pojo,把模板需要的数据都放入数据集。
Map root = new HashMap();
root.put("hello", "hello freemarker");
Person person = new Person("杰克",25,"北京市");
List<Person> persons = new ArrayList();
persons.add(new Person("杰克1",21,"北京市1"));
persons.add(new Person("杰克2",22,"北京市2"));
persons.add(new Person("杰克3",23,"北京市3"));
persons.add(new Person("杰克4",24,"北京市4"));
persons.add(new Person("杰克5",25,"北京市5"));
root.put("persons", persons);
root.put("cur_time", new Date());
root.put("val",null);
//第八步:创建一个Writer对象,指定生成的文件保存的路径及文件名。
Writer out = new FileWriter(new File("D:\\template\\freemarker\\second.html"));
//第九步:调用模板对象的process方法生成静态文件。需要两个参数数据集和writer对象。
template.process(root, out);
//第十步:关闭writer对象。
out.flush();
out.close();
}
3.Freemarker模板的写法
3.1 取简单数据类型数据
使用EL表达式。如:${hello}
3.2 设置常量
<#assign 变量名="变量值">
使用 ${变量名} 取值
注意:对比JSTL中<c:set value="${xxx}" var="xx">
3.3 取包装数据类型
${person.name},${person.age},${person.address}
3.4 遍历集合/数组
List<Person> persons = new ArrayList<Person>();
页面中显示内容
<#list persons as p>
当前索引值:${p_index}
姓名:${p.name}
年龄:${p.age}
</#list>
注意:对比JSTL中 <c:forEach items="${xxx}" var="当前元素名">
3.5 模板中判断条件
<#if 判断条件>
<#else>
3.6 日期类型格式化
默认格式
1:date
curtime?date2:datetime
{cur_time?datetime}
3:time
${cur_time?time}
自定义格式
${cur_time?string(“yyyy-MM-dd HH:mm:ss”)}
3.7 处理null值
root.put(“val”,null);
解决办法
1. null 变 空串
${val!}
2. 为Null时给默认值
${val!“我是默认值"}
3.
<#if val ??>
不为空的执行语句
<#else>
为空的执行语句
</#if>
3.8 include标签
将另一个页面引入本页面时可用以下命令完成
<#include "/include/head.ftl">
Freemarker整合spring
使用freemarker整合spring。把Configuration交给spring容器管理。
依赖的jar包:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
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>
获得Configuration对象
Configuration configuration = freeMarkerConfigurer.getConfiguration();