分享

java利用freemarker生成html静态页面

 江江385 2013-03-29

    提升网站性能的方式有很多,例如有效的使用缓存,生成静态页面等等。今天要说的就是生成静态页面的方式。使用html静态页面是为了保证最快的反应速度,毕竟html 比jsp少了一层服务器执行.速度上要快的多
   FreeMarker 是一个用java编写的模版引擎,主要用来生成web html页面,通常由java程序准备要显示的数据,与FreeMarker 生成静态页面.

     编写ftl模版可以生成html代码,必须导入freemarker包

核心代码:

  1.    private Configuration tempConfiguration; 

  2.   public void setTempConfiguration(Configuration tempConfiguration) {
            this.tempConfiguration = tempConfiguration;
        }

  1.     public static void crateHTML(ServletContext context,  

  2.            Map<String, Object> data, String templatePath, String targetHtmlPath) {

  3.         try { 

  4.              //filepath:ftl存放路径(/template/file/static)

  5.             this.tempConfiguration.setDirectoryForTemplateLoading(new File(filePath)); 

  6.            //templatePath:ftl文件名称(template.ftl)

  7.             Template template = this.tempConfiguration.getTemplate(templatePath);  

  8.             template.setEncoding("UTF-8");  

  9.             // 静态页面要存放的路径  

  10.             String htmlPath = targetHtmlPath;  

  11.             File htmlFile = new File(htmlPath);  

  12.             Writer out = new BufferedWriter(new OutputStreamWriter(  

  13.                     new FileOutputStream(htmlFile), "UTF-8"));  

  14.             // 处理模版 map数据 ,输出流

  15.             template.process(data, out);  

  16.             out.flush();  

  17.             out.close();  

  18.         } catch (Exception e) {  

  19.             e.printStackTrace();  

  20.         }  

  21.     }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多