1、简介
网页静态化解决方案在实际开发中运用比较多,例如新闻网站,门户网站中的新闻频道,或者是文章类的频道。对于电商网站的商品详细页来说,至少几百万个商品,每个商品又有大量的信息,这样的情况同样也适用于使用网页静态化来解决。
网页静态化技术和缓存技术的共同点都是为了减轻数据库的访问压力,但是具体的应用场景不同,缓存比较适合小规模的数据,而网页静态化比较适合大规模且相对变化不太频繁的数据。另外网页静态化还有利于SEO,另外我们如果将网页以纯静态化的形式展现。
2、原理
3、入门小demo
1>引入依赖
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> |
2>创建模板文件
模板文件中四种元素
1、文本,直接输出的部分
2、注释,即<#--...-->格式不会输出
3、插值(Interpolation):即${..}部分,将使用数据模型中的部分替代输出
4、FTL指令:FreeMarker指令,和HTML标记类似,名字前加#予以区分,不会输出。
我们现在就创建一个简单的创建模板文件test.ftl
<HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>FREEMARKER入门小DEMO </title> </HEAD> <BODY> <#--我只是一个注释,我不会有任何输出--> <#include "head.ftl"> ${name},你好! ${message}<br/> <#assign LINKMAN="周先生"> 联系人:${LINKMAN}<br/> <#if success=true> 您已经通过了实名认证 <#else> 您未经通过了实名认证 </#if> <br/> ----商品信息------<br/> <#list goodsList as goods> ${goods_index+1} 商品名称: ${goods.name} 商品价格 ${goods.price} <br/> </#list> 一共有 ${goodsList?size} 条记录<br/>
----JSON 转成对象------<br/> <#assign text="{'bank':'工商银行','account':'10101920201920212'}" /> <#assign data=text?eval /> 开户行:${data.bank} 账号:${data.account} <br/>
----时间显示------<br/> 当前日期:${today?date} <br> 当前时间:${today?time} <br> 当前日期+时间:${today?datetime} <br> 日期格式化: ${today?string("yyyy年MM月")}<br> ----数字转换为字符串------<br/> 累计积分:${point?c}<br/> ----判断某变量是否存在------<br/> <#if aaa??> aaa变量存在 ${aaa} <#else> aaa变量不存在 </#if> ${aaa!'-'}
</BODY> </HTML> |
head.ftl
<h1>信息网</h1> |
3> Test. java文件
public class Test {
public static void main(String[] args) throws IOException, TemplateException {
Configuration configuration=new Configuration(Configuration.getVersion()); configuration.setDirectoryForTemplateLoading(new File("G:\\pro\\freemakerDemo\\src\\main\\resources"));
configuration.setDefaultEncoding("UTF-8"); Template template = configuration.getTemplate("test.ftl");
Map map = new HashMap(); map.put("name", "张三"); map.put("message", "欢迎来到神奇的freemaker世界!"); map.put("success", false);
List goodsList=new ArrayList(); Map goods1=new HashMap(); goods1.put("name", "苹果"); goods1.put("price", 5.8); Map goods2=new HashMap(); goods2.put("name", "香蕉"); goods2.put("price", 2.5); Map goods3=new HashMap(); goods3.put("name", "橘子"); goods3.put("price", 3.2); goodsList.add(goods1); goodsList.add(goods2); goodsList.add(goods3); map.put("goodsList", goodsList);
map.put("today", new Date());
map.put("point", 102920122);
String inter_folder_file="g:\\freemaker"; File tagFile = new File(inter_folder_file,"a.html"); Writer out = new PrintWriter(tagFile,"UTF-8"); template.process(map, out); out.close();
} } |
4、基本语法
1>assign指令
此指令用于在页面上定义一个变量
2>include指令
此指令用于模板文件的嵌套
3>if指令 参考demo
4>list指令参考demo
5>集合大小:内置size命令
6>json转字符串,见demo
7>显示时间,见demo
8>数字转字符串,见demo
9>判断变量是否存在,见demo
10>判断缺少值,见demo