FreeMarker 语法 访问 pojo 的属性

一、java 代码

@Test
public void testFreeMarker() throws Exception {
    //1、创建一个模板文件
    //2、创建一个Configuration对象
    Configuration configuration = new Configuration();
    //3、设置模板文件保存的目录
    configuration.setDirectoryForTemplateLoading(new File("E:/workspaces/fw-item-web/src/main/webapp/WEB-INF/ftl"));
    //4、模板文件的编码格式,一般就是utf-8
    configuration.setDefaultEncoding("utf-8");
    //5、加载一个模板文件,创建一个模板对象。
    Template template = configuration.getTemplate("student.ftl");
    //6、创建一个数据集。可以是pojo也可以是map。推荐使用map
    Map data = new HashMap<>();
//创建一个 pojo 对象 Student student = new Student(1, "张三", 18); data.put("student", student); //7、创建一个Writer对象,指定输出文件的路径及文件名。 Writer out = new FileWriter(new File("E:/freemarker/student.html")); //8、生成静态页面 template.process(data, out); //9、关闭流 out.close(); }

二、student.ftl 模板代码

<html>
<head>
    <title>student</title>
</head>
<body>
    学生信息:<br>
    id:${student.id}&nbsp;&nbsp;&nbsp;&nbsp;
    姓名:${student.name}&nbsp;&nbsp;&nbsp;&nbsp;
    年龄:${student.age}&nbsp;&nbsp;&nbsp;&nbsp;
</body>
</html>

三、运行结果

原文地址:https://www.cnblogs.com/fangwu/p/8696193.html