提升网站性能的方式有很多,例如有效的使用缓存,生成静态页面等等。今天要说的就是生成静态页面的方式。使用html静态页面是为了保证最快的反应速度,毕竟html 比jsp少了一层服务器执行.速度上要快的多 FreeMarker 是一个用java编写的模版引擎,主要用来生成web html页面,通常由java程序准备要显示的数据,与FreeMarker 生成静态页面. 编写ftl模版可以生成html代码,必须导入freemarker包
核心代码:
private Configuration tempConfiguration;
public void setTempConfiguration(Configuration tempConfiguration) { this.tempConfiguration = tempConfiguration; }
public static void crateHTML(ServletContext context, Map<String, Object> data, String templatePath, String targetHtmlPath) {
try {
//filepath:ftl存放路径(/template/file/static)
this.tempConfiguration.setDirectoryForTemplateLoading(new File(filePath));
//templatePath:ftl文件名称(template.ftl) Template template = this.tempConfiguration.getTemplate(templatePath); template.setEncoding("UTF-8"); // 静态页面要存放的路径 String htmlPath = targetHtmlPath; File htmlFile = new File(htmlPath); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(htmlFile), "UTF-8")); // 处理模版 map数据 ,输出流
template.process(data, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
|