网页静态化方案Freemarker
#
概念:
事先将数据从数据库提取出来,生成文件,用户访问时直接访问文件,不需要访问数据库,减少数据库的访问压力,同时还有利于SEO(搜索引擎优化)。
1.Freemarker介绍
- 一个用java语言编写的模板引擎,基于模板来生成文本输出。FreeMarker与 Web 容器无关,即在 Web 运行时,它并不知道 Servlet 或 HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成 XML,JSP 或 Java 等。
2.入门demo
依赖
<dependencies> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> </dependencies>
demo
-
public static void main(String[] args) throws Exception {
//获取配置类
Configuration configuration = new Configuration(Configuration.getVersion());
//设置编码
configuration.setDefaultEncoding(“utf-8”);
//设置模板所在路径
configuration.setDirectoryForTemplateLoading(new File(“E:/eclipse_32/workspace/freemarker/src/main/resources”));
//根据模板文件获取模板对象
Template template = configuration.getTemplate(“template.ftl”);
//设置变量信息
Map map = new HashMap<>();
map.put(“name”, “吴彦祖”);
map.put(“message”, “欢迎来到freemarker”);
map.put(“flag”, true);
//设置集合对象
List list = new ArrayList<>();
Map map1 = new HashMap<>();
map1.put(“name”, “刘德华”);
map1.put(“age”, 25);
map1.put(“address”, “香港”);
Map map2 = new HashMap<>();
map2.put(“name”, “张学友”);
map2.put(“age”, 28);
map2.put(“address”, “铜锣湾”);
Map map3 = new HashMap<>();
map3.put(“name”, “周星驰”);
map3.put(“age”, 27);
map3.put(“address”, “九龙”);
list.add(map1);
list.add(map2);
list.add(map3);
map.put(“list”, list);
//设置JSON字符串对象
map.put(“json”, “{‘name’:’tony’,’age’:20,’address’:’Hongkong’}”);
//设置数字
map.put(“money”, 123456789);
//设置日期对象
map.put(“date”, new Date());
//获取输出流(指定输出文件名)
Writer out = new FileWriter(new File(“d:/test.html”));
//生成对象
template.process(map, out);
out.close();
}
3.FTL指令
- assign指令:<#assign sender=”———–吴彦祖”>
- include指令:<#include “head.ftl”>
if指令:
<#if flag==true> flag现在等于true <#else> flag竟然是false </#if>
list指令:
<#list list as item> <br> ${item_index+1} 姓名:${item.name} 年龄:${item.age} 地址:${item.address} </#list>
3.内建函数:(变量+?+函数名称)
- 获取集合大小: 共${list?size}条记录。
转换JSON字符串为对象:
<#assign text="{'bank':'工商银行','account':'10101920201920212'}" /> <#assign data=text?eval />
日期格式化:
dataModel.put("today", new Date()); 在模板文件中加入 当前日期:${today?date} <br> 当前时间:${today?time} <br> 当前日期+时间:${today?datetime} <br> 日期格式化: ${today?string("yyyy年MM月")}
数字转为字符串:(不加c,将会没三位添加一个,分隔符)
你猜我有多少钱:${money?c}
4.运算符
空值处理运算符:
<#if sex??> 判断是否存在 </#if> <#--缺失变量默认值--> ${sex!'假的'} <br>
算数运算符:
减法:${(money-10000)?c}
逻辑运算符:
<#if (1000>500)&&(1000<2000)> 1000在2000与500之间! </#if>
- 比较运算符:
1000大于500吗?
<#if 1000 gt 500>
是的!
<#else>
不,并不大于!