freemarker语法与介绍

什么是freemarker

FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。

目前企业中:主要用Freemarker做静态页面或是页面展示


Freemarker的使用方法

Maven工程添加依赖

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>
  1. 先创建一个ftl文件
    这里写图片描述
    hello.ftl文件路径
  2. java实现代码
    @Test
    public void genFile() throws Exception {
        // 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 第二步:设置模板文件所在的路径。
        configuration.setDirectoryForTemplateLoading(new File("D:/JAVAGIT/e3/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 dataModel = new HashMap<>();
        //向数据集中添加数据
        dataModel.put("hello", "this is my first freemarker test.");
        // 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
        Writer out = new FileWriter(new File("D:/temp/hello.html"));
        // 第七步:调用模板对象的process方法输出文件。
        template.process(dataModel, out);
        // 第八步:关闭流。
        out.close();
    }

freemarker语法

  1. student.ftl文件代码
<html>
<head>
    <title>student</title>
</head>
<body>
    学生信息:<br>
    学号:${student.id}&nbsp;&nbsp;&nbsp;&nbsp;
    姓名:${student.name}&nbsp;&nbsp;&nbsp;&nbsp;
    年龄:${student.age}&nbsp;&nbsp;&nbsp;&nbsp;
<br>
    学生列表:
<table border="1">
        <tr>
            <th>序号</th>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
        </tr>
        <!-- 遍历 -->
        <#list stuList as stu>
        <!-- 判断  -->
        <#if stu_index % 2 == 0>
        <tr bgcolor="red">
        <#else>
        <tr bgcolor="green">
        </#if>
            <!--显示条数  -->
            <td>${stu_index}</td>
            <td>${stu.id}</td>
            <td>${stu.name}</td>
            <td>${stu.age}</td>
        </tr>
        </#list>
    </table>
    <br>

    <!-- 可以使用?date,?time,?datetime,?string(parten)-->
    当前日期:${date?string("yyyy/MM/dd HH:mm:ss")}<br>
    null值的处理:${val!"val的值为null"}<br>
    判断val的值是否为null:<br>
    <#if val??>
    val中有内容
    <#else>
    val的值为null
    </#if>
    引用模板测试:<br>
    <#include "hello.ftl">
</body>
</html>
  1. java代码

    /**
     * pojod 测试
     * @throws Exception
     */
    @Test
    public void  freemarkerPojo() throws Exception{

        // 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
                Configuration configuration = new Configuration(Configuration.getVersion());
                // 第二步:设置模板文件所在的路径。
                configuration.setDirectoryForTemplateLoading(new File("D:/JAVAGIT/e3/e3-item-web/src/main/webapp/WEB-INF/ftl"));
                // 第三步:设置模板文件使用的字符集。一般就是utf-8.

                configuration.setDefaultEncoding("utf-8");
                // 第四步:加载一个模板,创建一个模板对象。
                Template template = configuration.getTemplate("student.ftl");
                // 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。
                Map dataModel = new HashMap<>();
                Student student = new Student(1, "aa", 10);
                //向数据集中添加数据
                dataModel.put("student", student);

                //添加数组
                List<Student> arrayList = new ArrayList<Student>();
                arrayList.add(new Student(1, "n11", 11));
                arrayList.add(new Student(2, "n22", 22));
                arrayList.add(new Student(3, "n33", 33));
                arrayList.add(new Student(4, "n44", 44));
                arrayList.add(new Student(5, "n55", 55));
                arrayList.add(new Student(6, "n66", 66));
                arrayList.add(new Student(7, "n77", 77));
                arrayList.add(new Student(8, "n88", 88));
                arrayList.add(new Student(9, "n99", 99));
                arrayList.add(new Student(10, "n100", 100));
                dataModel.put("stuList",arrayList);

                //添加日期类型
                dataModel.put("date", new Date());
                //null值的测试
                dataModel.put("val", "123");

                //hello赋值
                dataModel.put("hello", "123");

                // 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
                Writer out = new FileWriter(new File("D:/temp/hello.html"));
                // 第七步:调用模板对象的process方法输出文件。
                template.process(dataModel, out);
                // 第八步:关闭流。
                out.close();
    }

student.ftl文件地址

java代码地址


freemarker与spring整合

  1. 引入jar包:
    Freemarker的jar包
    这里写图片描述

  2. 创建整合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>
  1. web.xml配置
    加载所有的配置文件
    这里写图片描述

  2. 测试

package cn.e3mall.item.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 测试freemarker与spring配置测试
 * @author yuhf
 *
 */
@Controller
public class FreemarkerSpringTest {

    @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.ftld");
        // 4、创建数据集
        Map dataModel = new HashMap<>();
        dataModel.put("hello", "1000");
        // 5、创建输出文件的Writer对象。
        Writer out = new FileWriter(new File("D:/temp/spring-freemarker.html"));
        // 6、调用模板对象的process方法,生成文件。
        template.process(dataModel, out);
        // 7、关闭流。
        out.close();
        return "OK";
    }
}

猜你喜欢

转载自blog.csdn.net/yuhaifei_123/article/details/79380725