• springmvc视图格式——模板引擎freemarker输出HTML文本


    1. freemarker 介绍

    ​ FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

    ​ freemarker作为springmvc一种视图格式,默认情况下SpringMVC支持freemarker视图格式。

    需要创建Spring Boot+Freemarker工程用于测试模板。

    创建测试工程

    创建一个freemarker-demo 的测试工程专门用于freemarker的功能测试与模板的测试。

    pom.xml如下

    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>heima-leadnews-testartifactId>
            <groupId>com.heimagroupId>
            <version>1.0-SNAPSHOTversion>
        parent>
        <modelVersion>4.0.0modelVersion>
    
        <artifactId>freemarker-demoartifactId>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-freemarkerartifactId>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
            dependency>
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
            dependency>
    
            
            <dependency>
                <groupId>org.apache.commonsgroupId>
                <artifactId>commons-ioartifactId>
                <version>1.3.2version>
            dependency>
        dependencies>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    2.2.2) 配置文件

    配置application.yml

    server:
      port: 8881 #服务端口
    spring:
      application:
        name: freemarker-demo #指定服务名
      freemarker:
        cache: false  #关闭模板缓存,方便测试
        settings:
          template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
        suffix: .ftl               #指定Freemarker模板文件的后缀名
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    2.2.3) 创建模型类

    在freemarker的测试工程下创建模型类型用于测试

    package com.heima.freemarker.entity;
    
    import lombok.Data;
    
    import java.util.Date;
    
    @Data
    public class Student {
        private String name;//姓名
        private int age;//年龄
        private Date birthday;//生日
        private Float money;//钱包
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    2.2.4) 创建模板

    在resources下创建templates,此目录为freemarker的默认模板存放目录。

    在templates下创建模板文件 01-basic.ftl ,模板中的插值表达式最终会被freemarker替换成具体的数据。

    DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello World!title>
    head>
    <body>
    <b>普通文本 String 展示:b><br><br>
    Hello ${name} <br>
    <hr>
    <b>对象Student中的数据展示:b><br/>
    姓名:${stu.name}<br/>
    年龄:${stu.age}
    <hr>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    2.2.5) 创建controller

    创建Controller类,向Map中添加name,最后返回模板文件。

    package com.xuecheng.test.freemarker.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.client.RestTemplate;
    
    import java.util.Map;
    
    @Controller
    public class HelloController {
    
        @GetMapping("/basic")
        public String test(Model model) {
    
    
            //1.纯文本形式的参数
            model.addAttribute("name", "freemarker");
            //2.实体类相关的参数
            
            Student student = new Student();
            student.setName("小明");
            student.setAge(18);
            model.addAttribute("stu", student);
    
            return "01-basic";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    01-basic.ftl,使用插值表达式填充数据

    DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello World!title>
    head>
    <body>
    <b>普通文本 String 展示:b><br><br>
    Hello ${name} <br>
    <hr>
    <b>对象Student中的数据展示:b><br/>
    姓名:${stu.name}<br/>
    年龄:${stu.age}
    <hr>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    2.2.6) 创建启动类
    package com.heima.freemarker;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class FreemarkerDemotApplication {
        public static void main(String[] args) {
            SpringApplication.run(FreemarkerDemotApplication.class,args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    2.2.7) 测试

    请求:http://localhost:8881/basic
    在这里插入图片描述

    2.3) freemarker基础

    2.3.1) 基础语法种类

    1、注释,即<#-- -->,介于其之间的内容会被freemarker忽略

    <#--我是一个freemarker注释-->
    
    • 1

    2、插值(Interpolation):即 ${..} 部分,freemarker会用真实的值代替**${..}**

    Hello ${name}
    
    • 1

    3、FTL指令:和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑。

    <# >FTL指令 
    
    • 1

    4、文本,仅文本信息,这些不是freemarker的注释、插值、FTL指令的内容会被freemarker忽略解析,直接输出内容。

    <#--freemarker中的普通文本-->
    我是一个普通的文本
    
    • 1
    • 2
    2.3.2) 集合指令(List和Map)

    1、数据模型:

    在HelloController中新增如下方法:

    @GetMapping("/list")
    public String list(Model model){
    
        //------------------------------------
        Student stu1 = new Student();
        stu1.setName("小强");
        stu1.setAge(18);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());
    
        //小红对象模型数据
        Student stu2 = new Student();
        stu2.setName("小红");
        stu2.setMoney(200.1f);
        stu2.setAge(19);
    
        //将两个对象模型数据存放到List集合中
        List<Student> stus = new ArrayList<>();
        stus.add(stu1);
        stus.add(stu2);
    
        //向model中存放List集合数据
        model.addAttribute("stus",stus);
    
        //------------------------------------
    
        //创建Map数据
        HashMap<String,Student> stuMap = new HashMap<>();
        stuMap.put("stu1",stu1);
        stuMap.put("stu2",stu2);
        // 3.1 向model中存放Map数据
        model.addAttribute("stuMap", stuMap);
    
        return "02-list";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    2、模板:

    在templates中新增02-list.ftl文件

    DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello World!title>
    head>
    <body>
        
    <#-- list 数据的展示 -->
    <b>展示list中的stu数据:b>
    <br>
    <br>
    <table>
        <tr>
            <td>序号td>
            <td>姓名td>
            <td>年龄td>
            <td>钱包td>
        tr>
    table>
    <hr>
        
    <#-- Map 数据的展示 -->
    <b>map数据的展示:b>
    <br/><br/>
    <a href="###">方式一:通过map['keyname'].propertya><br/>
    输出stu1的学生信息:<br/>
    姓名:<br/>
    年龄:<br/>
    <br/>
    <a href="###">方式二:通过map.keyname.propertya><br/>
    输出stu2的学生信息:<br/>
    姓名:<br/>
    年龄:<br/>
    
    <br/>
    <a href="###">遍历map中两个学生信息:a><br/>
    <table>
        <tr>
            <td>序号td>
            <td>姓名td>
            <td>年龄td>
            <td>钱包td> 
        tr>
    table>
    <hr>
     
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    实例代码:

    DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello World!title>
    head>
    <body>
        
    <#-- list 数据的展示 -->
    <b>展示list中的stu数据:b>
    <br>
    <br>
    <table>
        <tr>
            <td>序号td>
            <td>姓名td>
            <td>年龄td>
            <td>钱包td>
        tr>
        <#list stus as stu>
            <tr>
                <td>${stu_index+1}td>
                <td>${stu.name}td>
                <td>${stu.age}td>
                <td>${stu.money}td>
            tr>
        #list>
    
    table>
    <hr>
        
    <#-- Map 数据的展示 -->
    <b>map数据的展示:b>
    <br/><br/>
    <a href="###">方式一:通过map['keyname'].propertya><br/>
    输出stu1的学生信息:<br/>
    姓名:${stuMap['stu1'].name}<br/>
    年龄:${stuMap['stu1'].age}<br/>
    <br/>
    <a href="###">方式二:通过map.keyname.propertya><br/>
    输出stu2的学生信息:<br/>
    姓名:${stuMap.stu2.name}<br/>
    年龄:${stuMap.stu2.age}<br/>
    
    <br/>
    <a href="###">遍历map中两个学生信息:a><br/>
    <table>
        <tr>
            <td>序号td>
            <td>姓名td>
            <td>年龄td>
            <td>钱包td>
        tr>
        <#list stuMap?keys as key >
            <tr>
                <td>${key_index}td>
                <td>${stuMap[key].name}td>
                <td>${stuMap[key].age}td>
                <td>${stuMap[key].money}td>
            tr>
        #list>
    table>
    <hr>
     
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    👆上面代码解释:

    ${k_index}:
    index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始

    2.3.3) if指令

    ​ if 指令即判断指令,是常用的FTL指令,freemarker在解析时遇到if会进行判断,条件为真则输出if中间的内容,否则跳过内容不再输出。

    • 指令格式
    <#if >if>
    
    • 1

    1、数据模型:

    使用list指令中测试数据模型,判断名称为小红的数据字体显示为红色。

    2、模板:

    
        <#list stus as stu>
            
    姓名 年龄 钱包
    ${stu.name} ${stu.age} ${stu.mondy}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    实例代码:

    
        <#list stus as stu >
            <#if stu.name='小红'>
                
                <#else >
                
    姓名 年龄 钱包
    ${stu_index} ${stu.name} ${stu.age} ${stu.money}
    ${stu_index} ${stu.name} ${stu.age} ${stu.money}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3、输出:

    姓名为“小强”则字体颜色显示为红色。
    在这里插入图片描述

    2.3.4) 运算符

    1、算数运算符

    FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:

    • 加法: +
    • 减法: -
    • 乘法: *
    • 除法: /
    • 求模 (求余): %

    模板代码

    <b>算数运算符b>
    <br/><br/>
        100+5 运算:  ${100 + 5 }<br/>
        100 - 5 * 5运算:${100 - 5 * 5}<br/>
        5 / 2运算:${5 / 2}<br/>
        12 % 10运算:${12 % 10}<br/>
    <hr>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    除了 + 运算以外,其他的运算只能和 number 数字类型的计算。

    2、比较运算符

    • =或者==:判断两个值是否相等.
    • !=:判断两个值是否不等.
    • >或者gt:判断左边值是否大于右边值
    • >=或者gte:判断左边值是否大于等于右边值
    • <或者lt:判断左边值是否小于右边值
    • <=或者lte:判断左边值是否小于等于右边值

    = 和 == 模板代码

    DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello World!title>
    head>
    <body>
    
        <b>比较运算符b>
        <br/>
        <br/>
    
        <dl>
            <dt> =/== 和 != 比较:dt>
            <dd>
                <#if "xiaoming" == "xiaoming">
                    字符串的比较 "xiaoming" == "xiaoming"
                #if>
            dd>
            <dd>
                <#if 10 != 100>
                    数值的比较 10 != 100
                #if>
            dd>
        dl>
    
    
    
        <dl>
            <dt>其他比较dt>
            <dd>
                <#if 10 gt 5 >
                    形式一:使用特殊字符比较数值 10 gt 5
                #if>
            dd>
            <dd>
                <#-- 日期的比较需要通过?date将属性转为data类型才能进行比较 -->
                <#if (date1?date >= date2?date)>
                    形式二:使用括号形式比较时间 date1?date >= date2?date
                #if>
            dd>
        dl>
    
        <br/>
    <hr>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    Controller 的 数据模型代码

    @GetMapping("operation")
    public String testOperation(Model model) {
        //构建 Date 数据
        Date now = new Date();
        model.addAttribute("date1", now);
        model.addAttribute("date2", now);
        
        return "03-operation";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    比较运算符注意

    • **=!=**可以用于字符串、数值和日期来比较是否相等
    • **=!=**两边必须是相同类型的值,否则会产生错误
    • 字符串 "x""x " 、**"X"**比较是不等的.因为FreeMarker是精确比较
    • 其它的运行符可以作用于数字和日期,但不能作用于字符串
    • 使用**gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>**解释成FTL标签的结束字符
    • 可以使用括号来避免这种情况,如:<#if (x>y)>

    3、逻辑运算符

    • 逻辑与:&&
    • 逻辑或:||
    • 逻辑非:!

    逻辑运算符只能作用于布尔值,否则将产生错误 。

    模板代码

    <b>逻辑运算符b>
        <br/>
        <br/>
        <#if (10 lt 12 )&&( 10  gt  5 )  >
            (10 lt 12 )&&( 10  gt  5 )  显示为 true
        #if>
        <br/>
        <br/>
        <#if !false>
            false 取反为true
        #if>
    <hr>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    2.3.5) 空值处理

    1、判断某变量是否存在使用 “??”

    用法为:variable??,如果该变量存在,返回true,否则返回false

    例:为防止stus为空报错可以加上判断如下:

        <#if stus??>
        <#list stus as stu>
        	......
        
        
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2、缺失变量默认值使用 “!”

    • 使用!要以指定一个默认值,当变量为空时显示默认值

      例: ${name!‘’}表示如果name为空显示空字符串。

    • 如果是嵌套对象则建议使用()括起来

      例: ${(stu.bestFriend.name)!‘’}表示,如果stu或bestFriend或name为空默认显示空字符串。

    2.3.6) 内建函数

    内建函数语法格式: 变量+?+函数名称

    1、和到某个集合的大小

    ${集合名?size}

    2、日期格式化

    显示年月日: ${today?date}
    显示时分秒:${today?time}
    显示日期+时间:${today?datetime}
    自定义格式化: ${today?string("yyyy年MM月")}

    3、内建函数c

    model.addAttribute(“point”, 102920122);

    point是数字型,使用${point}会显示这个数字的值,每三位使用逗号分隔。

    如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出

    ${point?c}

    4、将json字符串转成对象

    一个例子:

    其中用到了 assign标签,assign的作用是定义一个变量。

    <#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
    <#assign data=text?eval />
    开户行:${data.bank}  账号:${data.account}
    
    • 1
    • 2
    • 3

    模板代码:

    
    
    
        
        inner Function
    
    
    
        获得集合大小
    集合大小:
    获得日期
    显示年月日:
    显示时分秒:
    显示日期+时间:
    自定义格式化:

    内建函数C
    没有C函数显示的数值:
    有C函数显示的数值:
    声明变量assign

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    内建函数模板页面:

    
    
    
        
        inner Function
    
    
    
        获得集合大小
    集合大小:${stus?size}
    获得日期
    显示年月日: ${today?date}
    显示时分秒:${today?time}
    显示日期+时间:${today?datetime}
    自定义格式化: ${today?string("yyyy年MM月")}

    内建函数C
    没有C函数显示的数值:${point}
    有C函数显示的数值:${point?c}
    声明变量assign
    <#assign text="{'bank':'工商银行','account':'10101920201920212'}" /> <#assign data=text?eval /> 开户行:${data.bank} 账号:${data.account}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    内建函数Controller数据模型:

    @GetMapping("innerFunc")
    public String testInnerFunc(Model model) {
        //1.1 小强对象模型数据
        Student stu1 = new Student();
        stu1.setName("小强");
        stu1.setAge(18);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());
        //1.2 小红对象模型数据
        Student stu2 = new Student();
        stu2.setName("小红");
        stu2.setMoney(200.1f);
        stu2.setAge(19);
        //1.3 将两个对象模型数据存放到List集合中
        List<Student> stus = new ArrayList<>();
        stus.add(stu1);
        stus.add(stu2);
        model.addAttribute("stus", stus);
        // 2.1 添加日期
        Date date = new Date();
        model.addAttribute("today", date);
        // 3.1 添加数值
        model.addAttribute("point", 102920122);
        return "04-innerFunc";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    2.4) 静态化测试

    之前的测试都是SpringMVC将Freemarker作为视图解析器(ViewReporter)来集成到项目中,工作中,有的时候需要使用Freemarker原生Api来生成静态内容,下面一起来学习下原生Api生成文本文件。

    2.4.1) 需求分析

    使用freemarker原生Api将页面生成html文件,本节测试html文件生成的方法:

    在这里插入图片描述

    2.4.2) 静态化测试

    根据模板文件生成html文件

    ①:修改application.yml文件,添加以下模板存放位置的配置信息,完整配置如下:

    server:
      port: 8881 #服务端口
    spring:
      application:
        name: freemarker-demo #指定服务名
      freemarker:
        cache: false  #关闭模板缓存,方便测试
        settings:
          template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
        suffix: .ftl               #指定Freemarker模板文件的后缀名
        template-loader-path: classpath:/templates   #模板存放位置
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ②:在test下创建测试类

    package com.heima.freemarker.test;
    
    
    import com.heima.freemarker.FreemarkerDemoApplication;
    import com.heima.freemarker.entity.Student;
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.*;
    
    @SpringBootTest(classes = FreemarkerDemoApplication.class)
    @RunWith(SpringRunner.class)
    public class FreemarkerTest {
    
        @Autowired
        private Configuration configuration;
    
        @Test
        public void test() throws IOException, TemplateException {
            //freemarker的模板对象,获取模板
            Template template = configuration.getTemplate("02-list.ftl");
            Map params = getData();
            //合成
            //第一个参数 数据模型
            //第二个参数  输出流
            template.process(params, new FileWriter("d:/list.html"));
        }
    
        private Map getData() {
            Map<String, Object> map = new HashMap<>();
    
            //小强对象模型数据
            Student stu1 = new Student();
            stu1.setName("小强");
            stu1.setAge(18);
            stu1.setMoney(1000.86f);
            stu1.setBirthday(new Date());
    
            //小红对象模型数据
            Student stu2 = new Student();
            stu2.setName("小红");
            stu2.setMoney(200.1f);
            stu2.setAge(19);
    
            //将两个对象模型数据存放到List集合中
            List<Student> stus = new ArrayList<>();
            stus.add(stu1);
            stus.add(stu2);
    
            //向map中存放List集合数据
            map.put("stus", stus);
    
    
            //创建Map数据
            HashMap<String, Student> stuMap = new HashMap<>();
            stuMap.put("stu1", stu1);
            stuMap.put("stu2", stu2);
            //向map中存放Map数据
            map.put("stuMap", stuMap);
    
            //返回Map
            return map;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    在这里插入图片描述

    在这里插入图片描述

  • 相关阅读:
    Android NDK JNI 开发native层崩溃日志栈分析 空指针异常(Cause: null pointer dereference)
    Magnet: Push-based Shuffle Service for Large-scale Data Processing
    如何处理前端响应式图片?
    小黑子—spring:第一章 Bean基础
    Android 11 替换Launcher后导致近期任务无效
    跨越技术鸿沟,革新存储产业:华瑞指数云重磅发布下一代软件定义存储产品
    抖音、快手、视频号排兵布阵VR直播
    lintcode 584 · 丢鸡蛋II 【中等 vip 动态规划】
    【Android】源码中的建造者模式
    WPF实战项目十五(客户端):RestSharp的使用
  • 原文地址:https://blog.csdn.net/qq_59708493/article/details/133934842