创建maven工程codeutil,并引入响应坐标
<dependencies>
<!--freemarker核心包 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
(1)创建模板template.ftl
欢迎您:${username}
(2)使用freemarker完成操作
public class FreemarkTest01 {
@Test
public void testProcessTemplate() throws Exception {
//1.创建freeMarker配置实例
Configuration cfg = new Configuration();
//2.设置模板加载器:开始加载模板,并且把模板加载在缓存中
cfg.setTemplateLoader(new FileTemplateLoader(new File("templates")));
//3.创建数据模型
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("username", "张三");
//4.获取模板
Template template = cfg.getTemplate("temp01.ftl");
//
/**
* 5.处理模板内容(i.输出到文件)
* process:
* 参数一:数据模型(map集合)
* 参数二:Writer对象(文件,控制台)
*/
//i.输出到文件
//template.process(dataModel, new FileWriter(new
File("C:\\Users\\ThinkPad\\Desktop\\ihrm\\day12\\测试\\aa.text")));
//i.打印到控制台
template.process(dataModel, new PrintWriter(System.out));//在控制台输出内容
}
}
public class FreemarkTest02 {
private Configuration conf;
@Before
public void init() {
conf = new Configuration();
}
@Test
public void testProcessTemplateString() throws Exception {
String templateString = "欢迎您:${username}";
Map<String,Object> dataMap = new HashMap();
dataMap.put("username","张三");
StringWriter out = new StringWriter();
/**
* 自定义模板
* 1.模板名称
* 2.模板的正文内容
* 3.configuration对象
*/
Template template = new Template("templateString...",new StringReader(templateString),conf);
//处理模板内容
template.process(dataMap, out);
System.out.println(out.toString());
}
}
FreeMarker模板文件主要有5个部分组成:
FreeMarker(还有模板开发者)并不关心数据是如何计算的,FreeMarker 只是知道真实的数据是什么。模板能用的所有数据被包装成 data-model 数据模型
在FreeMarker模板中可以包括下面几个特定部分:
<#if condition>
....
<#elseif condition2>
...
<#elseif condition3>
...
<#else>
...`在这里插入代码片`
</#if>
<#list sequence as item>
...
</#list>
除此之外,迭代集合对象时,还包括两个特殊的循环变量:
a、item_index:当前变量的索引值。
b、item_has_next:是否存在下一个对象
也可以使用<#break>指令跳出迭代
<#list ["星期一","星期二","星期三","星期四","星期五"] as x>
${x_index +1}.${x} <#if x_has_next>,</#if>
<#if x = "星期四"><#break></#if>
</#list>
<#include filename [options]></#include>
在上面的语法格式中,两个参数的解释如下
a、filename:该参数指定被包含的模板文件
b、options:该参数可以省略,指定包含时的选项,包含encoding和parse两个选项,encoding
指定包含页面时所使用的解码集,而parse指定被
包含是否作为FTL文件来解析。如果省略了parse选项值,则该选项值默认是true
<#assign name = zhangsan />
?html:html字符转义
?cap_first: 字符串的第一个字母变为大写形式
?lower_case :字符串的小写形式
?upper_case :字符串的大写形式
?trim:去掉字符串首尾的空格
?substring:截字符串
?lenth: 取长度
?size: 序列中元素的个数
?int : 数字的整数部分(比如- 1.9?int 就是- 1)
?replace:字符串替换