记录项目一中页面静态化技术
1.概念:
静态化在页面上的体现为:访问速度加快,用户体验性明显提升;在后台体现为:访问脱离数据库,减轻了数据库访问压力。以空间换取时间。
2.使用技术:
FreeMarker实现页面静态化:
FreeMarker是一个基于Java的开发包和类库的一种将模板和数据进行整合并输出文本的通用工具,FreeMarker实现页面静态化 的原理是:将页面中所需要的样式写入到FreeMarker模板文件中,然后将页面所需要的数据进行动态绑定并放入到Map中,然后通 过FreeMarker的模板解析类process()方法完成静态页面的生成。
3.步骤:
- 导入freemarker.jar
- 获取模板(Template)对象
- 准备数据
- template.process()生成静态资源
- 创建xxx.ftl模板
4.获取模板对象代码:
public static String createFile(String path, String name, Object data, String suffix) {
FileWriter out = null;
try {
// 2.获取模板(Template)对象
// 2.1获取Configuration对象 --为了获取模板对象
Configuration config = new Configuration(Configuration.VERSION_2_3_28);
// 2.2设置默认加载路径
File file = new File(path);
config.setDirectoryForTemplateLoading(file);
config.setDefaultEncoding("utf-8");
// 2.4获取模板
Template template = config.getTemplate(name);
//3.准备数据
String url = System.currentTimeMillis()+suffix;
//4.template.process()生成静态资源
out = new FileWriter(new File(file, url));
template.process(data, out);
return url;
} catch (Exception e) {
e.printStackTrace();
}finally {
if(out!=null) {
try {
out.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return null;
}