freemarker

一、  概述

freemarker是java编写的一款模版引擎,是一种基于模版和要改变的数据,并用于输出文本(html、电子邮件、配置文件和源代码等)的通用工具。与web容器无关,即在web运行时,它并不知道servlet或HTTP。不仅可以用于表现层的实现技术,还可以用于生成XML,JPS或java等。在企业中,一般用于生成静态页面或是页面展示。

二、  使用freemarker

导入jar包或者引入依赖。

编写测试程序。

创建一个最简单的模版

在webapp的WEB-INF目录下,新建ftl目录,新建hello.ftl,一般是ftl后缀,也可以使用其他的。

${hello}

测试程序

    @Test

    publicvoid testFreemarker() throws Exception {

        // 创建模版文件

        // 创建Configuration对象

        Configuration configuration = newConfiguration(Configuration.getVersion());

        // 设置模版文件的保存路径

        configuration.setDirectoryForTemplateLoading(

                new File("H:\\001java\\eclipseSTSworkspace\\e3-item-web\\src\\main\\webapp\\WEB-INF\\ftl"));

        // 设置默认文件的编码格式,一般是utf-8

        configuration.setDefaultEncoding("utf-8");

        // 加载一个模版文件,创建一个模版对象

        Template template = configuration.getTemplate("hello.ftl");

        // 创建一个数据集,pojo或者map

        Map map = newHashMap<>();

        map.put("hello", "你好福瑞马克");

        // 创建一个Writer对象,指定输出文件的路径名及文件名

        Writer out = new FileWriter(new File("H:\\vv\\hello.txt"));

        // 生成静态页面

        template.process(map, out);

        // 关闭流

        out.close();

    }

三、  freemarker语法

1.        访问pojo属性

创建一个student的pojo。

创建模版

<!DOCTYPE html>

<html>

<head>

    <metacharset="utf-8" />

    <title>学生</title>

</head>

<body>

    学生信息<br />

    <table>

        <tr>

            <td>id</td>

            <td>姓名</td>

            <td>年龄</td>

            <td>地址</td>

        </tr>

        <tr>

            <td>${student.id}</td>

            <td>${student.name}</td>

            <td>${student.age}</td>

            <td>${student.address}</td>

        </tr>

    </table>

</body>

</html>

编写根据模版创建html文件的方法。 

    @Test

    public void testFreemarker2()throws Exception {

        // 创建模版文件

        // 创建Configuration对象

        Configuration c
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值