//简单的test方法测试
//1.创建一个模板文件
//2.创建一个Configuration对象
Configuration configurable = new Configuration(Configuration.getVersion());
//3.设置模板文件保存的目录
configurable.setDirectoryForTemplateLoading(new File("D:/template-mars2/e3-item-web/src/main/webapp/WEB-INF/ftl"));
//4.模板文件的编码格式,一般就是utf-8
configurable.setDefaultEncoding("utf-8");
//5.加载一个模板文件,创建一个模板对象。
// Template template = configurable.getTemplate("hell.ftl");
Template template = configurable.getTemplate("student.ftl");
//6.创建一个数据集。可以是pojo也可以是map.推荐使用map
Map data = new HashMap<>();
//创建一个pojo对象
Student student = new Student(1, "小明", 18, "回龙观");
data.put("student", student);
data.put("hello", "hello freemarker!");
//添加List形式
List studentList = new ArrayList<>();
studentList.add(new Student(1, "小明1", 18, "回龙观"));
studentList.add(new Student(2, "小明2", 19, "回龙观"));
studentList.add(new Student(3, "小明3", 20, "回龙观"));
studentList.add(new Student(4, "小明4", 21, "回龙观"));
studentList.add(new Student(5, "小明5", 22, "回龙观"));
studentList.add(new Student(6, "小明6", 23, "回龙观"));
studentList.add(new Student(7, "小明7", 24, "回龙观"));
studentList.add(new Student(8, "小明8", 25, "回龙观"));
studentList.add(new Student(9, "小明9", 26, "回龙观"));
data.put("studentList", studentList);
//添加日期类型
data.put("date", new Date());
//null值的测试
data.put("val", "12");
//7.创建一个Writer对象,指定输出文件的路径及文件名。D:\text
// Writer out = new FileWriter(new File("D:/text/hello.txt"));
Writer out = new FileWriter(new File("D:/text/student.html"));
//8.生成静态页面
template.process(data, out);
//9.关闭流
out.close();
配置上面是需要注意的是 //5.加载一个模板文件,创建一个模板对象 文件内容
student
学生信息:
学号:${student.id}
姓名:${student.name}
年龄:${student.age}
家庭住址:${student.address}
学生列表:
序号 |
学号 |
姓名 |
年龄 |
家庭住址 |
<#list studentList as stu>
<#if stu_index % 2 == 0>
<#else>
#if>
${stu_index} |
${stu.id} |
${stu.name} |
${stu.age} |
${stu.address} |
#list>
当前日期:${date?string("yyyy/MM/dd HH:mm:ss")}
null值的处理:${val!"val的值为null"}
判断val的值是否为null:
<#if val??>
val中有内容
<#else>
val的值为null
#if>
引用模板测试:
<#include "hell.ftl">
执行上面这段代码会在D:/text下生成一个student.html文件
下面是在springmvc中配置
在spring中测试
@Autowired
private FreeMarkerConfig freeMarkerConfig;
@RequestMapping("/genhtml")
@ResponseBody
public String getHtml() throws Exception{
Configuration configuration = freeMarkerConfig.getConfiguration();
//加载模板对象
Template template = configuration.getTemplate("hell.ftl");
//创建一个数据集
Map data = new HashMap<>();
data.put("hello", 1234567);
//指定文件输出的路径及文件名
Writer out = new FileWriter(new File("D:/text/hello1.html"));
//输出文件
template.process(data, out);
//关闭流
out.close();