Freemarker

Maven工程添加依赖

 

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>

原理:

使用步骤:

第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。

第二步:设置模板文件所在的路径。

第三步:设置模板文件使用的字符集。一般就是utf-8.

第四步:加载一个模板,创建一个模板对象。

第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。

第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。

第七步:调用模板对象的process方法输出文件。

第八步:关闭流。

模板:${hello}

@Test
    public void genFile() throws Exception {
        // 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 第二步:设置模板文件所在的路径。
        configuration.setDirectoryForTemplateLoading(new File("D:/workspaces-itcast/term197/taotao-item-web/src/main/webapp/WEB-INF/ftl"));
        // 第三步:设置模板文件使用的字符集。一般就是utf-8.
        configuration.setDefaultEncoding("utf-8");
        // 第四步:加载一个模板,创建一个模板对象。
        Template template = configuration.getTemplate("hello.ftl");
        // 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。
        Map dataModel = new HashMap<>();
        //向数据集中添加数据
        dataModel.put("hello", "this is my first freemarker test.");
        // 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
        Writer out = new FileWriter(new File("D:/temp/term197/out/hello.html"));
        // 第七步:调用模板对象的process方法输出文件。
        template.process(dataModel, out);
        // 第八步:关闭流。
        out.close();
    }

hello.ftl

${hello}

模板的语法

1.访问map中的key

${key}

${key.property}

2.访问pojo中的属性

<html>
<head>
    <title>测试页面</title>
</head>
<body>
    学生信息:<br>
    学号:${student.id}<br>
    姓名:${student.name}<br>
    年龄:${student.age}<br>
    家庭住址:${student.address}<br>
    学生列表:<br>
    <table border="1">
        <tr>
            <th>序号</th>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>家庭住址</th>
        </tr>
        <#list stuList as stu>
        <#if stu_index%2==0>
        <tr bgcolor="red">
        <#else>
        <tr bgcolor="blue">
        </#if>
            <td>${stu_index}</td>
            <td>${stu.id}</td>
            <td>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.address}</td>
        </tr>
        </#list>
    </table>
    <br>
    日期类型的处理:${date?string("yyyy/MM/dd HH:mm:ss")}
    <br>
    null值的处理:${val!}
    <br>
    使用if判断null值:
    <#if val??>
    val是有值的。。。
    <#else>
    val值为null。。。
    </#if>
    <br>
    include标签测试:
    <#include "hello.ftl">
</body>
</html>

 取集合中的数据

<#list studentList as student>

${student.id}/${studnet.name}

</#list>

循环使用格式:

<#list 要循环的数据 as 循环后的数据>

</#list>

 取循环中的下标

<#list studentList as student>

${student_index}

</#list>

判断

<#if student_index % 2 == 0>

<#else>

</#if>

日期类型格式化

直接取值:${date}(date是属性名)如果传来的是一个Date型数据会报错
${date?date} 2016-9-13
${date?time} 17:53:55
${date?datetime} 2016-9-13 17:53:55

Null值的处理

如果直接取一个不存在的值(值为null)时会报异常

${aaa}

处理: ${aaa!”默认值}或者${aaa! }代表空字符串

  Include标签

<#include “模板名称”>

(相当于jstl中的包含)

Freemarker整合spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <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>


</beans>

 Controller

请求的url:/genhtml

参数:无

返回值:ok (String, 需要使用@ResponseBody)

业务逻辑:

1、从spring容器中获得FreeMarkerConfigurer对象。

2、从FreeMarkerConfigurer对象中获得Configuration对象。

3、使用Configuration对象获得Template对象。

4、创建数据集

5、创建输出文件的Writer对象。

6、调用模板对象的process方法,生成文件。

7、关闭流。

加载配置文件:

 

@Controller
public class HtmlGenController {
    
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @RequestMapping("/genhtml")
    @ResponseBody
    public String genHtml()throws Exception {
        // 1、从spring容器中获得FreeMarkerConfigurer对象。
        // 2、从FreeMarkerConfigurer对象中获得Configuration对象。
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        // 3、使用Configuration对象获得Template对象。
        Template template = configuration.getTemplate("hello.ftl");
        // 4、创建数据集
        Map dataModel = new HashMap<>();
        dataModel.put("hello", "1000");
        // 5、创建输出文件的Writer对象。
        Writer out = new FileWriter(new File("D:/temp/term197/out/spring-freemarker.html"));
        // 6、调用模板对象的process方法,生成文件。
        template.process(dataModel, out);
        // 7、关闭流。
        out.close();
        return "OK";
    }
}

 

posted @ 2020-05-03 12:31  苏先生139  阅读(176)  评论(0编辑  收藏  举报