收藏 分销(赏)

freemarker生成html.doc

上传人:天**** 文档编号:3560829 上传时间:2024-07-09 格式:DOC 页数:61 大小:329.50KB 下载积分:14 金币
下载 相关 举报
freemarker生成html.doc_第1页
第1页 / 共61页
freemarker生成html.doc_第2页
第2页 / 共61页


点击查看更多>>
资源描述
为了减轻服务器压力,将原来的文章管理系统由JSP文件的从数据库中取数据显示改为由jsp生成静态html文件后直接访问html文件。下面是一个简单的示例 1.buildhtml.jsp <%@ page contentType="text/html; charset=gb2312" import="java.util.*,java.io.*"%> <% try{ String title="This is Title"; String content="This is Content Area"; String editer="LaoMao"; String filePath = ""; filePath = request.getRealPath("/")+"test/template.htm"; //out.print(filePath+"<br/>"); String templateContent=""; FileInputStream fileinputstream = new FileInputStream(filePath);//读取模块文件 int lenght = fileinputstream.available(); byte bytes[] = new byte[lenght]; fileinputstream.read(bytes); fileinputstream.close(); templateContent = new String(bytes); //out.print(templateContent); templateContent=templateContent.replaceAll("###title###",title); templateContent=templateContent.replaceAll("###content###",content); templateContent=templateContent.replaceAll("###author###",editer);//替换掉模块中相应的地方 //out.print(templateContent); // 根据时间得文件名 Calendar calendar = Calendar.getInstance(); String fileame = String.valueOf(calendar.getTimeInMillis()) +".html"; fileame = request.getRealPath("/")+fileame;//生成的html文件保存路径 FileOutputStream fileoutputstream = new FileOutputStream(fileame);//建立文件输出流 byte tag_bytes[] = templateContent.getBytes(); fileoutputstream.write(tag_bytes); fileoutputstream.close(); } catch(Exception e){ out.print(e.toString()); } %> 2. template.htm <html> <head> <title>###title###</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <LINK href="../css.css" rel=stylesheet type=text/css> </head> <body> <table width="500" border="0" align="center" cellpadding="0" cellspacing="2"> <tr> <td align="center">###title###</td> </tr> <tr> <td align="center">author:###author###&nbsp;&nbsp;</td> </tr> <tr> <td>###content### </td> </tr> </table> </body> </html> 用freemarker模版生成静态html 2007-07-11 4:28 pm  睬一踩 |                Rss订阅|         以前写过,不过忘记了。   参考/修改了网上的一个例子,代码如下: NewsItem .java package freemarker; /**  * @author terrychan  *  */ public class NewsItem { public String title; public String addTime; public String showContent; public String getAddTime() {  return addTime; } public void setAddTime(String addTime) {  this.addTime = addTime; } public String getTitle() {  return title; } public void setTitle(String title) {  this.title = title; } public String getShowContent() {  return showContent; } public void setShowContent(String showContent) {  this.showContent = showContent; } public void loadData(){    this.title=”测试内容”;    this.showContent=”测试freemarker生成静态页面”;    this.addTime=”2007-09-10″; } }  FreeMarkerTest.java package freemarker; import java.io.*; import java.util.HashMap; import java.util.Map; import mons.logging.Log; import mons.logging.LogFactory; import freemarker.template.*; /**  * 测试FreeMarker.  *  * @author Terry.Chan  *  */ public class FreeMarkerTest {  private final Log logger = LogFactory.getLog(getClass());  private Configuration freemarker_cfg = null;  static String sGeneFilePath = “d:\\test\\”;  static String sGeneFileName = “freemarker.htm”;  static String sTempPlateFilePath = “d:\\test\\”;  public static void main(String[] args) throws IOException {   // @todo 创建一个类,然后创建instance   NewsItem aItem = new NewsItem();   aItem.loadData();   FreeMarkerTest test = new FreeMarkerTest();   Map root = new HashMap();   root.put(”newsitem”, aItem);   boolean bOK = test.geneHtmlFile(”template.ftl”, root, sGeneFilePath,     sGeneFileName);  }  /**   * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.   */  protected Configuration getFreeMarkerCFG() {   if (null == freemarker_cfg) {    // Initialize the FreeMarker configuration;    // - Create a configuration instance    freemarker_cfg = new Configuration();    // - FreeMarker支持多种模板装载方式,可以查看API文档,都很简单:路径,根据Servlet上下文,classpath等等    // htmlskin是放在classpath下的一个目录    // freemarker_cfg.setClassForTemplateLoading(this.getClass(),    // “/htmlskin”);    // freemarker_cfg.setTemplateLoader(arg0)    // freemarker_cfg.set    try {     freemarker_cfg.setDirectoryForTemplateLoading(new File(       sTempPlateFilePath));    } catch (Exception ex) {     ex.printStackTrace();    }   }   return freemarker_cfg;  }  /**   * 生成静态文件.   *   * @param templateFileName   *            模板文件名,相对htmlskin路径,例如”/tpxw/view.ftl”   * @param propMap   *            用于处理模板的属性Object映射   * @param htmlFilePath   *            要生成的静态文件的路径,相对设置中的根路径,例如 “/tpxw/1/2005/4/”   * @param htmlFileName   *            要生成的文件名,例如 “1.htm”   */  public boolean geneHtmlFile(String templateFileName, Map propMap,    String htmlFilePath, String htmlFileName) {   // @todo 从配置中取得要静态文件存放的根路径:需要改为自己的属性类调用   try {    Template t = getFreeMarkerCFG().getTemplate(templateFileName);    // 如果根路径存在,则递归创建子目录    creatDirs(htmlFilePath);    File afile = new File(htmlFilePath + “/” + htmlFileName);    Writer out = new BufferedWriter(new OutputStreamWriter(      new FileOutputStream(afile)));    t.process(propMap, out);   } catch (TemplateException e) {    logger.error(”Error while processing FreeMarker template ”      + templateFileName, e);    return false;   } catch (IOException e) {    logger.error(”Error while generate Static Html File ”      + htmlFileName, e);    return false;   }   return true;  }  /**   * 创建多级目录   *   * @param aParentDir   *            String   * @param aSubDir   *            以 / 开头   * @return boolean 是否成功   */  public static boolean creatDirs(String path) {   File aFile = new File(path);   if (!aFile.exists()) {    return aFile.mkdirs();   } else {    return true;   }  } } template.ftl  <html> <head> <title>查看文章: ${newsitem.title} </title> </head> <body> <table width=”100%” border=”0″ cellpadding=”0″ cellspacing=”0″ bgcolor=”#FFFFFF”> <tr><td> <table width=”95%” border=”0″ align=”center” cellpadding=”2″ cellspacing=”6″ >     <tr>       <td height=”10″ align=”left” colspan=2 ></td>     </tr>     <tr>            <td align=”left” width=”538″ >            <strong>${newsitem.title}</strong> ( ${newsitem.addTime} )           </td>           <td align=”right”>             <a href=”index.jsp” mce_href=”index.jsp”>返回</a>                                </td>     </tr>     <tr>                               <td align=”left” valign=top colspan=2>          <hr align=”left”  width=”95%” size=”1″ noshade color=”#cc0000″ >          </td>     </tr>     <tr>                            <td colspan=2>${newsitem.showContent}       </td>     </tr> </table>                        <br> </td></tr> </table> </body> </html> < html >      < head >          < title > 查看文章: $ {newsitem.title}   </ title >      </ head >      < body >          < table width = " 100% "  border = " 0 "  cellpadding = " 0 "  cellspacing = " 0 "  bgcolor = " #FFFFFF " >              < tr >                  < td >                      < table width = " 95% "  border = " 0 "  align = " center "  cellpadding = " 2 "  cellspacing = " 6 "   >                          < tr >                              < td height = " 10 "  align = " left "  colspan = 2   ></ td >                          </ tr >                          < tr >                              < td align = " left "  width = " 538 "   >                                  < strong > $ {newsitem.title} </ strong >  ( $ {newsitem.addtime}  )                              </ td >                              < td align = " right " >                                  < a href = " index.jsp " > 返回 </ a >                                  & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;                              </ td >                          </ tr >                          < tr >                              < td align = " left "  valign = top colspan = 2 >                                  < hr align = " left "   width = " 95% "  size = " 1 "  noshade color = " #cc0000 "   >                              </ td >                          </ tr >                          < tr >                              < td colspan = 2 > $ {newsitem.showContent} </ td >                          </ tr >                      </ table >                      < br >                  </ td >              </ tr >          </ table >      </ body > </ html >   代码:   import  java.io. * ; import  java.util.HashMap;  import  java.util.Map;  import  mons.logging.Log;  import  mons.logging.LogFactory;  import  freemarker.template. * ;  /**/ /* * Created on 2005-4-7   *    */      /** */ /**    * 测试FreeMarker.   *   *  @author  scud   *    */   public   class  FreeMarkerTest  {              private   final  Log logger  =  LogFactory.getLog(getClass());                    private  Configuration freemarker_cfg  =   null ;                                      public   static   void  main(String[] args)           {               // @todo 自己的一个类              NewsItem aItem  =   null ;                            // @todo 装入新闻               // NewsItem = loadNewsItem(1);                               FreeMarkerTest test  =   new  FreeMarkerTest();                           Map root  =   new  HashMap();              root.put( " newsitem " , aItem);                 String sGeneFilePath  =   " /tpxw/ " ;                           String sFileName  =   " 1.htm " ;                  boolean  bOK  =  test.geneHtmlFile( " /tpxw/view.ftl " ,root, sGeneFilePath,sFileName);                       }                        /** */ /**            * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.            */            protected  Configuration getFreeMarkerCFG()           {               if  ( null   ==  freemarker_cfg)               {                   //  Initialize the FreeMarker configuration;                   //  - Create a configuration instance                  freemarker_cfg  =   new  Configuration();                      //  - FreeMarker支持多种模板装载方式,可以查看API文档,都很简单:路径,根据Servlet上下文,classpath等等                                    // htmlskin是放在classpath下的一个目录                  freemarker_cfg.setClassForTemplateLoading( this .getClass(),  " /htmlskin " );              }                             return  freemarker_cfg;          }               /** */ /**            * 生成静态文件.           *           *  @param  templateFileName 模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl"           *  @param  propMap 用于处理模板的属性Object映射           *  @param  htmlFilePath 要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/"           *  @param  htmlFileName 要生成的文件名,例如 "1.htm"            */            public   boolean  geneHtmlFile(String templateFileName,Map propMap, String htmlFilePath,String htmlFileName )           {                  // @todo 从配置中取得要静态文件存放的根路径:需要改为自己的属性类调用              String sRootDir  =   " e:/webtest/htmlfile "  ;                            try                {                  Template t  =  getFreeMarkerCFG().getTemplate(templateFileName);                      // 如果根路径存在,则递归创建子目录                  creatDirs(sRootDir,htmlFilePath);                                   File afile  =   new  File(sRootDir  + " / "   + htmlFilePath  +   " / "   +  htmlFileName);                     Writer out  =   new  BufferedWriter( new  OutputStreamWriter( new  FileOutputStream(afile)));                     t.process(propMap, out);              }                catch  (TemplateException e)               {                  logger.error( " Error while processing FreeMarker template  "   +  templateFileName,e);                   return   false ;              }                catch  (IOException e)               {                  logger.error( " Error while generate Static Html File  "   +  htmlFileName,e);                   return   false ;              }                   return   true ;          }                                 /** */ /**            * 创建多级目录           *           *  @param  aParentDir String           *  @param  aSubDir  以 / 开头           *  @return  boolean 是否成功            */            public   static   boolean  creatDirs(String aParentDir, String aSubDir)           {              File aFile  =   new  File(aParentDir);               if  (aFile.exists())               {                  File aSubFile  =   new  File(aParentDir  +  aSubDir);                   if  ( ! aSubFile.exists())                   {                       return  aSubFile.mkdirs();                  }                    else                    {                       return   true ;                  }               }                else                {                   return   false ;              }           }      }   H hhhhh漫步 | 漫步资源站 Asp教程.Net教程PHP教程JSP教程数据库网页设计网络管理网站运作大杂烩 窗体顶端   Web 窗体底端 漫步统计系统2006个人版,降价了,每套仅需30元,详情请进... FreeMarker设计指南(1) JSP教程-Java技巧及代码             FreeMarker设计指南(1) 1、快速入门 (1)模板 + 数据模型 = 输出 l         FreeMarker基于设计者和程序员是具有不同专业技能的不同个体的观念 l         他们是分工劳动的:设计者专注于表示——创建HTML文件、图片、Web页面的其它可视化方面;程序员创建系统,生成设计页面要显示的数据 l         经常会遇到的问题是:在Web页面(或其它类型的文档)中显示的信息在设计页面时是无效的,是基于动态数据的 l         在这里,你可以在HTML(或其它要输出的文本)中加入一些特定指令,FreeMarker会在输出页面给最终用户时,用适当的数据替代这些代码 l         下面是一个例子: <html> <head>   <title>Welcome!</title> </head> <body>   <h1>Welcome ${user}!</h1>   <p>Our latest product:   <a href="${latestProduct.url}">${latestProduct.name}</a>! </body> </html>  l         这个例子是在简单的HTML中加入了一些由${…}包围的特定代码,这些特定代码是FreeMarker的指令,而包含FreeMarker的指令的文件就称为模板(Template) l         至于user、latestProduct.url和latestProduct.name来自于数据模型(data model) l         数据模型由程序员编程来创建,向模板提供变化的信息,这些信息来自于数据库、文件,甚至于在程序中直接生成 l         模板设计者不关心数据从那儿来,只知道使用已经建立的数据模型 l         下面是一个可能的数据模型: (root)   |   +- user = "Big Joe"   |   +- latestProduct       |       +- url = "products/greenmouse.html"       |       +- name = "green mouse" l         数据模型类似于计算机的文件系统,latestProduct可以看作是目录,而user、url和name看作是文件,url和name文件位于lates
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 包罗万象 > 大杂烩

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服