1. 什么是freemarker
freemarker是基于apache的licene2.0编写的模板引擎, 也叫模板框架2. freemarker干什么用的 通过模板+数据自动生成静态化页面 FTC.(freemarker模板)页面静态化优点:
1. 因为统一生成静态化页面, 那么客户访问的时候, 直接访问的是html这样不用经过tomcat编译, 所以客户显示的很快,增加良好的用户体验 2. 因为不用去后台获取数据, 所以可以降低数据库的访问压力提前生成好的,即商品上架时,发送给ActiveMq。
freemarker运用(12306,京东)
ftl 中写的都是页面模板 .html 可以用EL表达式,freemarker 支持。
freemarker 初始化对象,configuration();
eg:demo
public class FreemarkerTest{
public static void main(strin[] args) throws Exception{
//创建freemarker 初始化对象
Configuartion conf = new Configuration();
//加载模板所在的目录(注意目录要使用在硬盘上的位置的绝对路径)右键查看路径
conf.setDirectoryForTemplateLoading(new file("..\\绝对路\\.."));
//通过模板目录加载模板对象
Template template = conf.getTemplate("xxxx.html");
//传入模板的数据
map<string , object>rootMap =new hashMap<>();
rootMap.put("test","hello world");
//模拟List数据
Lsit<String> list =new ArrayList<String>();
list.add(''张三");
list.add(''李四");
rootMap.put("testList",list);
//模拟Map
Map<String ,String> testMap= new HashMap< >();
testMap.put("001","张三");
testMap.put("002","李四");
rootMap.put("testMap",testMap);
//设置静态页面生成的文件名称
writer out = new FileWriter(new File("test.html"));
//生成静态化页面,第一个参数为传入的数据,第二个参数为生成的静态化页面的位置
template.process(rootMap,out);
}
},
模板标签的使用;
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<title> Insert title here</title>
</head>
<body>
${world}<br/>
</body>
</html>
List集合遍历
<#list testList as testList>
${ testList}
</#list>
Map 遍历
<#list testMap? keys as key>
key: ${key}(key是临时变量) value: ${testMap[key]}
</#list>
判断
<#if xxx_index ==0 >
${xxx}
<#else>
${xxx}
<#if>
引入其他页面
<# include "xxx.html">
面试会问到freemarker 空值的问题;日后有机会在介绍freemaker的原理