主要是为了从后台抓数据,生成一个静态页面,
网络静态化技术和缓存技术的共同点都是为了减轻数据库的访问压力,具体应用的场景不同,缓存表叫适合小规模的数据,网页静态化比较适合大规模且相对变化不频繁的数据,网页静态化有利于SEO(搜索引擎的优化,网络营销)
将网页以纯静态化的形式展现,要使用Nginx这样的高性能的web服务器来部署,Nginx可以承载5W并发量,tomcat只有几百
Freemarker:
用java语言编写的模板引擎
模板文件四种元素
1、文本,直接输出的部分
2、注释,即<#--...-->格式不会输出
3、插值(Interpolation):即${..}部分,将使用数据模型中的部分替代输出,类似EL表达式
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
二、java程序
public static void main(String[] args) throws Exception {
{
//创建配置类,参数当期那版本号
Configuration configuration = new Configuration(Configuration.getVersion());
//设置模板所在目录
configuration.setDirectoryForTemplateLoading(new File("D:\\workspaces\\idea\\freemakertest\\src\\main\\resources\\ftl"));
//设置字符集
configuration.setDefaultEncoding("utf-8");
//加载模板,数据要传输到的模板的名称
Template template = configuration.getTemplate("test.ftl");
//创建数据模型,后台传输的数据
Map map=new HashMap();
map.put("name", "学员");
map.put("message", "欢迎来优就业学习!");
map.put("success", true);
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("today",new Date());
map.put("goodsList", goodsList);
map.put("point", 102920122);
//创建Writer对象,指定生成静态资源路径
FileWriter out = new FileWriter(new File("f:\\ftl.html"));
//输出,第一个参数是
template.process(map, out);
System.out.println("生成成功");
//关闭输出流
out.close();
}
三、模板页面
<html>
<head>
<meta charset="utf-8">
<title>Freemarker入门小DEMO </title>
</head>
<body>
<#--我只是一个注释,我不会有任何输出 -->
${name},你好。${message}
<hr/>
<#assign linkman="优就业小优">
联系人:${linkman}
<#assign info={"mobile":"1891882881",'address':'北京市朝阳区五方桥'} >
电话:${info.mobile} 地址:${info.address}
<hr/>
<#--包含静态页面-->
<#include "head.ftl"/>
<hr/>
<#--if语句判断-->
<#if success=true>
你已通过实名认证
<#else>
你未通过实名认证
</#if>
<hr/>
<#--获取list中对象列表数据-->
----商品价格表----<br>
<#list goodsList as goods>
${goods_index+1} 商品名称: ${goods.name} 价格:${goods.price}<br>
</#list>
<#--内建函数-->
共 ${goodsList?size} 条记录
<hr/>
<#--将json字符串转换为对象 -->
<#assign text="{'bank':'工商银行','account':'18901920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}
<hr/>
<#--日期格式化-->
<#--当前日期:2019-11-26-->
当前日期:${today?date} <br>
<#--当前时间:22:59:47-->
当前时间:${today?time} <br>
<#--当前日期+时间:2019-11-26 22:59:47-->
当前日期+时间:${today?datetime} <br>
<#--日期格式化: 2019年11月-->
日期格式化: ${today?string("yyyy年MM月")}
<hr/>
<#--数字转字符串,内建函数c-->
未格式化累计积分:${point} <br>
格式化累计积分:${point?c} <br>
<hr/>
<#--后台未传aaa-->
<#if aaa??>
aaa变量存在
<#else>
aaa变量不存在
</#if>
<#--后台传-->
<hr/>
${aaa!'-'}
</body>
</html>
四、效果图

来源:https://www.cnblogs.com/guanyuehao0107/p/11938973.html