编程随笔 编程随笔
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)

liyao52033

走运时,要想到倒霉,不要得意得过了头;倒霉时,要想到走运,不必垂头丧气。心态始终保持平衡,情绪始终保持稳定,此亦长寿之道
  • 前端
  • 后端
  • 星球项目
  • 开源项目
  • 海康AGV
  • 四向车
  • 工具类
  • 项目仓库

    • 部署仓库 (opens new window)
    • 代码仓库 (opens new window)
  • vuepress插件

    • 自动生成导航栏与侧边栏 (opens new window)
    • 评论系统 (opens new window)
    • 全文搜索 (opens new window)
    • 选项卡 (opens new window)
    • 自动生成sitemap (opens new window)
  • 自主开发插件

    • 批量操作frontmatter (opens new window)
    • 链接美化 (opens new window)
    • 折叠代码块 (opens new window)
    • 复制代码块 (opens new window)
  • springboot

    • MyBatis Plus使用
    • springboot2引入swagger3
    • EasyCaptcha验证码存入redis的使用
    • 常用方法
    • Elasticsearch全文搜索
    • canal同步mysql数据到es中
    • SpringSecurity使用
    • StringUtils 工具类使用
    • HTTP各种参数发送
    • EasyExcel之Excel导入导出
    • EasyExcel具体使用
    • FreeMarker 模板引擎入门
      • 一、简述
      • 二、环境搭建&快速入门
      • 三、FreeMarker指令语法
      • 四、静态渲染
      • 五、参考文章
    • FreeMarker生成文件及WEB使用
    • TrueLicense 创建及安装证书
  • 服务器相关

  • 腾讯云cos对象操作

  • 后端
  • springboot
华总
2023-11-19
0
0
目录

FreeMarker 模板引擎入门原创

# 一、简述


在线文档:http://freemarker.foofun.cn/ (opens new window)

FreeMarker 也是一款模板引擎技术,它是一种基于模板和要改变的数据,并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。当然它也是一个Java类库,可以将之作为一个普通的组件嵌入到我们的产品中。

FreeMarker被设计用来生成HTML Web页面,特别是基于MVC模式 (opens new window)的应用程序,将视图从业务逻辑中抽离出来,业务中不再包括视图的展示,而是将视图交给FreeMarker来输出。虽然FreeMarker具有一些编程的能力,但通常先让Java程序准备要显示的数据,然后再用FreeMarker生成具体页面。 1

使用的时候,我们只需提供模板(后缀名 .ftl)和 数据,freemarker便可以帮我们生成web页面。

常用的Java模板引擎:

  • Jsp、Freemarker、Thymeleaf 、Velocity 等。
  • Jsp 为 Servlet 专用,不能单独进行使用。(老牌的模板引擎)
  • Thymeleaf 为新技术,功能较为强大,但是执行的效率比较低。(SpringBoot推荐使用的模板引擎)
  • Velocity 从2010年更新完 2.0 版本后,便没有在更新。Spring Boot 官方在 1.4 版本后对此也不在支持,虽然 Velocity 在 2017 年版本得到迭代,但为时已晚。 (用的很少了)

# 二、环境搭建&快速入门


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

# 1、创建一个springboot工程

# 2、导入maven依赖(springmvc和freemarker)

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 3、修改application.yml配置:(关闭缓存、配置后缀名)

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

# 4、编写实体类和controller代码,为模板引擎提供数据

实体类

@Data 
public class Student {    
  private String name;//姓名    
  private int age;//年龄   
  private Date birthday;//生日    
}
1
2
3
4
5
6

controller代码

package com.yuzi.generator.Controller;

import com.yuzi.generator.model.entity.Student;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Date;


@Controller // 注意,这里是不能使用@RestController的,我们需要返回的是String类型的字符串,不能返回Json字符串
@Tag(name = "Freemarker")
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) {
        // 1.纯文本形式的参数
        model.addAttribute("name", "freemarker");//参数1属性名称(在页面中使用),参数2模板数据
        // 2.实体类相关的参数
        Student student = new Student() {
            {
                setName("小舞");
                setAge(18);
            }
        };
        model.addAttribute("stu", student);
        return "helloworld"; //模板文件名称
    }
}
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

# 5、在resources/templates/目录下创建helloworld.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

1700636616123

6、启动项目,访问接口测试:http://localhost:8081/hello

202311221435289

数据对应关系:

1700636654691

# 三、FreeMarker指令语法

# 1. 基础语法

1、freemarker的注释:即<#--xxx-->,不会解析成页面会被freemarker忽略掉。

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

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

Hello ${name}
1

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

<#xxx>FTL指令</#xxx> 
1

4、文本,仅文本信息,可以直接输出内容。

<#--freemarker中的普通文本-->
我是一个普通的文本
1
2

# 2. 集合指令(list和map)

# 2.1 遍历list

语法:

 <#list stus as stu></#list>
1

示例:

@GetMapping("/list")
public String list(Model model) {
    Student stu1 = new Student();
    stu1.setName("小三");
    stu1.setAge(18);
    stu1.setMoney(3000d);

    Student stu2 = new Student();
    stu2.setName("小五");
    stu2.setAge(19);
    stu2.setMoney(6000d);

    //将两个对象模型数据存放到List集合中
    List<Student> stus = new ArrayList<>();
    stus.add(stu1);
    stus.add(stu2);


    //向model中存放List集合数据
    model.addAttribute("stus", stus);
    return "list";//页面模板文件名称
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

list.ftl:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
<#-- list 数据的展示 -->
<b>展示list中的stu数据:</b>
<br>
<br>
<table border="1px solid #ccc" cellspacing="0" cellpadding="0">
    <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>
</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

1700636703643

# 2.2 遍历map

1、获取map中的值

map['keyname'].property
map.keyname.property
1
2

2、遍历map

//遍历map的key
<#list userMap?keys as key>
	key:${key}---value:${userMap["${key}"]}
<#list>
1
2
3
4

示例:

@GetMapping("/map")
public String map(Model model) {
    Student stu1 = new Student();
    stu1.setName("小三");
    stu1.setAge(18);
    stu1.setMoney(3000d);

    Student stu2 = new Student();
    stu2.setName("小五");
    stu2.setAge(19);
    stu2.setMoney(6000d);

    //将两个对象模型数据存放到Map集合中
    Map<String, Student> stuMap = new HashMap<String, Student>() {
        {
            put("stu1", stu1);
            put("stu2", stu2);
        }
    };

    //向model中存放List集合数据
    model.addAttribute("stuMap", stuMap);
    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

map.ftl:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
<#-- Map 数据的展示 -->
<b>map数据的展示:</b>
<br/><br/>
<a href="###">方式一:通过map['keyname'].property</a><br/>
输出stu1的学生信息:<br/>
姓名:${stuMap['stu1'].name} <br/>
年龄:${stuMap['stu1'].age} <br/>
<br/>
<a href="###">方式二:通过map.keyname.property</a><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 + 1}</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

1700636771754

# 3. if 指令

if指令格式:

<#if expression>
	true的逻辑
<#else>
    false的逻辑
</#if>
1
2
3
4
5

需求:在列表中判断学生为小五的数据字体显示为红色。

GetMapping("/if")
public String testIf(Model model) {
    Student stu1 = new Student();
    stu1.setName("小三");
    stu1.setAge(18);
    stu1.setMoney(3000d);

    Student stu2 = new Student();
    stu2.setName("小五");
    stu2.setAge(19);
    stu2.setMoney(6000d);

    //将两个对象模型数据存放到List集合中
    List<Student> stus = new ArrayList<>();
    stus.add(stu1);
    stus.add(stu2);


    //向model中存放List集合数据
    model.addAttribute("stus", stus);
    return "if";//页面模板文件名称
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
<#-- list 数据的展示 -->
<b>展示list中的stu数据:</b>
<br>
<br>
<table border="1px solid #ccc" cellspacing="0" cellpadding="0">
    <tr>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stus as stu>

        <#if stu.name='小五'>
            <tr style="color: red">
                <td>${stu_index+1}</td>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
            </tr>
            <#else>
                <tr>
                    <td>${stu_index+1}</td>
                    <td>${stu.name}</td>
                    <td>${stu.age}</td>
                    <td>${stu.money}</td>
                </tr>
        </#if>
    </#list>
</table>
</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

1700636847533

# 4. 运算符


FreeMarker也支持算数运算符、比较运算符、逻辑运算符

# 4.1 算数运算符


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

示例:

<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>
1234567
1
2
3
4
5
6
7
8

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

# 4.2 比较运算符

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

示例:

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

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

# 4.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

# 5. 空值处理


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

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

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

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

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

  • 使用 ! 要指定一个默认值,当变量为空时显示默认值。
    • 例如: ${name!''} 表示如果name为空显示空字符串。
    • 例如: ${stu!'小五'} 表示如果stu为空显示小五字符串。
  • 如果是嵌套对象,建议使用()括起来。
    • 例如: ${(stu.bestFriend.name)!''} 表示 如果stu或bestFriend或name为空默认显示空字符串。

# 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

# 四、静态渲染


动态渲染:数据是动态变化的。

静态渲染:数据是固定的,使用freemarker原生Api将页面生成静态html文件。

1700636881458

编写静态渲染代码:

@SpringBootTest
public class FreemarkerTest {

    @Autowired
    private Configuration configuration;

    /**
     * 静态渲染 :Configuration(获取模板)+Map(提供的数据)
     * @throws IOException
     * @throws TemplateException
     */
    @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"));
    }

    /**
     * 基础数据
     * @return
     */
    private Map getData() {
        Map<String, Object> map = new HashMap<>();

        //小五对象模型数据
        Student stu1 = new Student();
        stu1.setName("小五");
        stu1.setAge(18);
        stu1.setMoney(1000d);

        //小三对象模型数据
        Student stu2 = new Student();
        stu2.setName("小三");
        stu2.setMoney(200d);
        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
<!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>

    <#if stus??>
        <#list stus as stu>
            <#if stu.name=='小红'>
                <tr style="color:#ff0000">
                    <td>${stu_index + 1}</td>
                    <td>${stu.name}</td>
                    <td>${stu.age}</td>
                    <td>${stu.money}</td>
                </tr>
            <#else >
                <tr>
                    <td>${stu_index + 1}</td>
                    <td>${stu.name}</td>
                    <td>${stu.age}</td>
                    <td>${stu.money}</td>
                </tr>
            </#if>
        </#list>
    </#if>

    stus集合的大小:${stus?size}

</table>
<hr>

<#-- Map 数据的展示 -->
<b>map数据的展示:</b>
<br/><br/>
<a href="###">方式一:通过map['keyname'].property</a><br/>
输出stu1的学生信息:<br/>
姓名:${stuMap['stu1'].name}<br/>
年龄:${stuMap['stu1'].age}<br/>
<br/>
<a href="###">方式二:通过map.keyname.property</a><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 + 1}</td>
            <td>${stuMap[key].name}</td>
            <td>${stuMap[key].age}</td>
            <td>${stuMap[key].money}</td>
        </tr>
    </#list>
</table>
<hr>
<#--
当前的日期为:${today?datetime}<br>
当前的日期为:${today?string("yyyy年MM月")}-->

-----------------------------------------------------<br>
<#--${point?c}-->

</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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

启动测试方法后,会出现freemarker生成的静态html文件:

1700636975564 1700637026609

总结:

1700637071214

# 五、参考文章

FreeMarker官网 (opens new window)

项目笔记 (opens new window)

Spring Boot 整合 Freemarker 模板引擎—Spring中文网 (opens new window)

Freemarker 模板开发手册 (opens new window)

#后端#springboot#FreeMarker
上次更新: 2023/12/09 16:19:24
EasyExcel具体使用
FreeMarker生成文件及WEB使用

← EasyExcel具体使用 FreeMarker生成文件及WEB使用→

最近更新
01
element-plus多文件手动上传 原创
11-03
02
TrueLicense 创建及安装证书 原创
10-25
03
手动修改迅捷配置 原创
09-03
04
安装 acme.sh 原创
08-29
05
zabbix部署 原创
08-20
更多文章>
Copyright © 2023-2024 liyao52033
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式