一、什么是FreeMarker?
FreeMarker是一款主流的Java语言编写的模板引擎,即一种基于模板和要改变的数据,并用来生产输出文本(HTML网页、配置文件、电子邮件、源代码等)的通用工具。
二、应用场景
- 页面静态化应用
- 导出word、ppt、excel等复杂性的文档
三、FreeMarker的使用方法
- 将freemarker的依赖添加到工程的pom中。
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
2. 开发步骤:
public void testFreemarker() throws Exception {
//1.创建一个模板文件
//2.创建一个Configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
//3.设置模板所在的路径
configuration.setDirectoryForTemplateLoading(new File("D:/workspaces/item-web/src/main/webapp/WEB-INF/ftl"));
//4.设置模板的字符集,一般utf-8
configuration.setDefaultEncoding("utf-8");
//5.使用Configuration对象加载一个模板文件,需要指定模板文件的文件名。
Template template = configuration.getTemplate("student.ftl");
//6.创建一个数据集,可以是pojo也可以是map,推荐使用map
Map data = new HashMap<>();
data.put("hello", "hello freemarker");
Student student = new Student(1, "小米", 11, "北京昌平回龙观");
data.put("student", student);
List<Student> stuList = new ArrayList<>();
stuList.add(new Student(1, "小米", 11, "北京昌平回龙观"));
stuList.add(new Student(2, "小米2", 12, "北京昌平回龙观"));
stuList.add(new Student(3, "小米3", 13, "北京昌平回龙观"));
stuList.add(new Student(4, "小米4", 14, "北京昌平回龙观"));
stuList.add(new Student(5, "小米5", 15, "北京昌平回龙观"));
stuList.add(new Student(6, "小米6", 16, "北京昌平回龙观"));
stuList.add(new Student(7, "小米7", 17, "北京昌平回龙观"));
data.put("stuList", stuList);
//日期类型的处理
data.put("date", new Date());
data.put("val","123456");
//7.创建一个Writer对象,指定输出文件的路径及文件名。
Writer out = new FileWriter(new File("D:/temp/out/student.html"));
//8.使用模板对象的process方法输出文件。
template.process(data, out);
//9.关闭流
out.close();
}
3. 模板文件常用语法:
(1)取对象的属性,例如:
学生信息:<br>
学号:${student.id}<br>
姓名:${student.name}<br>
年龄:${student.age}<br>
家庭住址:${student.address}<br>
(2)循环list的使用,例如:
<#list stuList as stu>
${stu_index}
${stu.id}
${stu.name}
${stu.age}
${stu.address}
</#list>
(3)判断if的使用,例如:
<#if stu_index%2==0>
xxx
<#else>
yyy
</#if>
(4)日期类型处理,例如:
日期类型的处理:
${date?string("yyyy/MM/dd HH:mm:ss")}
${date?date} //yyyy-MM-dd
${date?time} //hh-mm-ss
${date?datetime} //yyyy-MM-dd hh-mm-ss
(5)null值的处理,例如:
null值的处理:${val!}
或者:
使用if判断null值:
<#if val??>
val是有值的。。。
<#else>
val值为null。。。
</#if>
(6)include标签使用,例如:
//在原ftl模板中使用以下可以引入其他的模板文件
<#include "hello.ftl">
4. freeemarker整合spring使用:
(1)、sping配置文件引入freemarker的配置
<!-- freemarker的配置 -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
(2)、服务中使用FreeMarker
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
public void xx(){
Configuration configuration = freeMarkerConfigurer.getConfiguration();
Template template = configuration.getTemplate("xxx.ftl");
Map data = new HashMap<>();
data.put("xxxx", xxxx);
Writer out = new FileWriter(HTML_OUT_PATH + ".html");
template.process(data, out);
out.close();
}
(3)、通常生成的静态化页面可以使用nginx服务进行访问。