您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# FreeMarker入门知识点有哪些
## 一、FreeMarker概述
### 1.1 什么是FreeMarker
FreeMarker是一款基于Java的**模板引擎**,主要用于生成文本输出(如HTML网页、电子邮件、配置文件等)。它通过将模板文件与数据模型结合,动态生成内容,实现了**表现层与业务逻辑的分离**。
### 1.2 核心特点
- **轻量级**:不依赖Servlet容器,可独立运行
- **模板+数据模型**:采用MVC设计模式
- **强类型语言**:支持严格的数据类型检查
- **国际化支持**:内置本地化处理机制
- **扩展性强**:支持自定义指令和函数
### 1.3 典型应用场景
```java
// Java代码集成示例
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDirectoryForTemplateLoading(new File("/templates"));
Template template = cfg.getTemplate("test.ftl");
Map<String, Object> data = new HashMap<>();
data.put("user", "John");
template.process(data, new PrintWriter(System.out));
<#-- 注释不会输出 -->
<html>
<head>
<title>${title!"默认标题"}</title> <#-- 使用默认值 -->
</head>
<body>
<#include "header.ftl"> <#-- 包含子模板 -->
<#-- 主要内容区 -->
</body>
</html>
指令 | 说明 | 示例 |
---|---|---|
<#if> |
条件判断 | <#if x > 0>Positive</#if> |
<#list> |
循环遍历 | <#list items as item>${item}</#list> |
<#assign> |
定义变量 | <#assign x = 10> |
<#macro> |
定义宏 | <#macro greet>Hello!</#macro> |
<#import> |
导入命名空间 | <#import "/libs/mylib.ftl" as my> |
<#-- 标量类型 -->
${stringVar} <#-- 字符串 -->
${numberVar?c} <#-- 数字转字符串 -->
${booleanVar?then("Y","N")} <#-- 布尔值 -->
<#-- 容器类型 -->
${listVar[0]} <#-- 列表索引 -->
${mapVar.key} <#-- Map取值 -->
${arrayVar?first} <#-- 数组首元素 -->
<#-- 安全导航操作符 -->
${user.address!.street!} <#-- 双保险空值处理 -->
<#-- 默认值设置 -->
${user.name!"匿名用户"}
<#-- 空值判断 -->
<#if user??>
用户存在
</#if>
转换需求 | 语法 | 示例 |
---|---|---|
数字转字符串 | ?c |
${num?c} |
日期格式化 | ?string(format) |
${now?string("yyyy-MM-dd")} |
字符串转数字 | ?number |
"123"?number |
HTML转义 | ?html |
${content?html} |
JSON序列化 | ?json |
${data?json} |
<#if score >= 90>
优秀
<#elseif score >= 60>
及格
<#else>
不及格
</#if>
<#-- switch-case等效实现 -->
<#switch animal>
<#case "dog">犬类<#break>
<#case "cat">猫科<#break>
<#default>其他动物
</#switch>
<#-- 基本列表遍历 -->
<#list users as user>
${user_index + 1}. ${user.name} <#-- _index内置变量 -->
</#list>
<#-- 使用分页参数 -->
<#list 1..100 as n>
${n}<#if n?is_even>, </#if>
<#if n % 10 == 0><br></#if>
</#list>
<#-- 哈希表遍历 -->
<#list map?keys as key>
${key}: ${map[key]}
</#list>
<#list items as item>
<#-- 可通过item_has_next判断是否最后一项 -->
${item}<#if !item_has_next>;</#if>
<#-- 完整状态对象 -->
当前索引: ${item?index}
是否是奇数行: ${item?item_cycle('odd','even')}
</#list>
<#-- 定义带参数的宏 -->
<#macro pagination totalPages currentPage>
<div class="pagination">
<#list 1..totalPages as page>
<a href="?page=${page}"
class="${(page == currentPage)?then('active','')}">
${page}
</a>
</#list>
</div>
</#macro>
<#-- 调用宏 -->
<@pagination totalPages=10 currentPage=3 />
// Java端实现TemplateMethodModel
public class UpperCaseMethod implements TemplateMethodModelEx {
public Object exec(List args) {
return args.get(0).toString().toUpperCase();
}
}
// 模板中使用
${upper("hello")} <#-- 输出HELLO -->
<#-- base.ftl 父模板 -->
<html>
<head><title><#block title>默认标题</#block></title></head>
<body>
<#block content>默认内容</#block>
</body>
</html>
<#-- child.ftl 子模板 -->
<#import "base.ftl" as layout>
<@layout>
<#block title>子页面标题</#block>
<#block content>
子页面特有内容
</#block>
</@layout>
模板组织原则:
_common.ftl
模块名_功能.ftl
性能优化:
// 配置模板缓存
cfg.setTemplateUpdateDelayMilliseconds(3600000); // 1小时更新检查
cfg.setCacheStorage(new StrongCacheStorage());
调试技巧:
<#-- 输出调试信息 -->
<#assign debug = true>
<#if debug>
<pre>${data?json}</pre>
</#if>
问题1:特殊字符转义
<#-- 禁用自动转义 -->
<#ftl output_format="plainText">
${'<script>'?no_esc} <#-- 或使用<#noescape>指令 -->
问题2:大数值精度丢失
<#-- 处理Long型ID -->
${bigNumber?string.computer} <#-- 保持完整精度 -->
问题3:日期时区问题
// Java端设置时区
cfg.setSQLDateAndTimeTimeZone(TimeZone.getDefault());
IDE插件:
测试工具:
# 命令行测试
java -jar freemarker.jar template.ftl data.json
可视化工具:
学习路径建议:掌握基础语法 → 理解数据模型 → 练习模板组合 → 深入宏开发 → 研究性能优化
版本注意:本文基于FreeMarker 2.3.31编写,部分语法可能需要调整以适应不同版本 “`
注:本文实际约3200字,可根据需要扩展具体示例或补充实战案例以达到精确字数要求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。