1、 为了减轻服务器压力,将原来的文章管理系统由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="Th
2、is is Content Area";
String editer="LaoMao";
String filePath = "";
filePath = request.getRealPath("/")+"test/template.htm";
//out.print(filePath+"
");
String templateContent="";
FileInputStream fileinputstream = new File
3、InputStream(filePath);//读取模块文件 int lenght = fileinputstream.available(); byte bytes[] = new byte[lenght]; fileinputstream.read(bytes); fileinputstream.close(); templateContent = new String(bytes); //out.print(templateContent);
4、 templateContent=templateContent.replaceAll("###title###",title); templateContent=templateContent.replaceAll("###content###",content); templateContent=templateContent.replaceAll("###author###",editer);//替换掉模块中相应的地方 //out.print(templateContent); // 根据时间得文件名
5、 Calendar calendar = Calendar.getInstance(); String fileame = String.valueOf(calendar.getTimeInMillis()) +".html"; fileame = request.getRealPath("/")+fileame;//生成的html文件保存路径 FileOutputStream fileoutputstream = new FileOutputStream(fileame);//建立文件输出流
6、 byte tag_bytes[] = templateContent.getBytes(); fileoutputstream.write(tag_bytes); fileoutputstream.close(); } catch(Exception e){ out.print(e.toString()); } %> 2. template.htm
7、itle>###title###
| ###title### |
| author:###author### |
| ###content### |
9、 用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
10、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 showC
11、ontent; } 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
12、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 Configuratio
13、n 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();
14、 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获取.
15、 */ protected Configuration getFreeMarkerCFG() { if (null == freemarker_cfg) { // Initialize the FreeMarker configuration; // - Create a configuration instance freemarker_cfg = new Configuration(); // - FreeMarker支持多种模板装载方式,可以查看API文档,都很简单:路径,根据Servlet上下文,classpath等等 // ht
16、mlskin是放在classpath下的一个目录 // freemarker_cfg.setClassForTemplateLoading(this.getClass(), // “/htmlskin”); // freemarker_cfg.setTemplateLoader(arg0) // freemarker_cfg.set try { freemarker_cfg.setDirectoryForTemplateLoading(new File( sTempPlateFilePath)); } catch (Exc
17、eption ex) { ex.printStackTrace(); } } return freemarker_cfg; } /** * 生成静态文件. * * @param templateFileName * 模板文件名,相对htmlskin路径,例如”/tpxw/view.ftl” * @param propMap * 用于处理模板的属性Object映射 * @param htmlFilePath * 要生成的静态文件的路径,相对设置中
18、的根路径,例如 “/tpxw/1/2005/4/” * @param htmlFileName * 要生成的文件名,例如 “1.htm” */ public boolean geneHtmlFile(String templateFileName, Map propMap, String htmlFilePath, String htmlFileName) { // @todo 从配置中取得要静态文件存放的根路径:需要改为自己的属性类调用 try { Template t = getFreeMarkerCFG().getT
19、emplate(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)
20、 { 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; } /** * 创建多级目录 * * @p
21、aram 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.f
22、tl
25、
| |||||||
26、F " > < tr > < td > < table width = " 95% " border = " 0 " align = " center " cellpadding = " 2 " cellspacing = " 6 " > < tr > < td height = " 10 " align = " left " colspan = 2
27、 > td > tr > < tr > < td align = " left " width = " 538 " > < strong > $ {newsitem.title} strong > ( $ {newsitem.addtime} ) td >
28、 < td align = " right " > < a href = " index.jsp " > 返回 a > & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; td > tr >
29、 < tr > < td align = " left " valign = top colspan = 2 > < hr align = " left " width = " 95% " size = " 1 " noshade color = " #cc0000 " > td > <
30、/ tr > < tr > < td colspan = 2 > $ {newsitem.showContent} td > tr > table > < br > td > tr > table >
31、 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. *
32、 * @author scud * */ public class FreeMarkerTest { private final Log logger = LogFactory.getLog(getClass()); private Configuration freemarker_cfg = null ; public static void main(String[] ar
33、gs) { // @todo 自己的一个类 NewsItem aItem = null ; // @todo 装入新闻 // NewsItem = loadNewsItem(1); FreeMarkerTest test = new FreeMarkerTest(); Map root =
34、 new HashMap(); root.put( " newsitem " , aItem); String sGeneFilePath = " /tpxw/ " ; String sFileName = " 1.htm " ; boolean bOK = test.geneHtmlFile( " /tpxw/view.ftl " ,root, sGeneFilePath,sFileName);
35、 } /** */ /** * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取. */ protected Configuration getFreeMarkerCFG() { if ( null == freemarker_cfg) { /
36、/ Initialize the FreeMarker configuration; // - Create a configuration instance freemarker_cfg = new Configuration(); // - FreeMarker支持多种模板装载方式,可以查看API文档,都很简单:路径,根据Servlet上下文,classpath等等 // htmls
37、kin是放在classpath下的一个目录 freemarker_cfg.setClassForTemplateLoading( this .getClass(), " /htmlskin " ); } return freemarker_cfg; } /** */ /** * 生成静态文件. * * @param templateFileNa
38、me 模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl" * @param propMap 用于处理模板的属性Object映射 * @param htmlFilePath 要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/" * @param htmlFileName 要生成的文件名,例如 "1.htm" */ public boolean geneHtmlFile(String templateFileNa
39、me,Map propMap, String htmlFilePath,String htmlFileName ) { // @todo 从配置中取得要静态文件存放的根路径:需要改为自己的属性类调用 String sRootDir = " e:/webtest/htmlfile " ; try { Template t = getFreeMarkerCFG().getTe
40、mplate(templateFileName); // 如果根路径存在,则递归创建子目录 creatDirs(sRootDir,htmlFilePath); File afile = new File(sRootDir + " / " + htmlFilePath + " / " + htmlFileName); Writer out = new Buffere
41、dWriter( new OutputStreamWriter( new FileOutputStream(afile))); t.process(propMap, out); } catch (TemplateException e) { logger.error( " Error while processing FreeMarker template " + templateFileName,e);
42、 return false ; } catch (IOException e) { logger.error( " Error while generate Static Html File " + htmlFileName,e); return false ; } return true ;
43、} /** */ /** * 创建多级目录 * * @param aParentDir String * @param aSubDir 以 / 开头 * @return boolean 是否成功 */ public static boolean creatDirs(String aParentDir, String aSubDir)
44、 { File aFile = new File(aParentDir); if (aFile.exists()) { File aSubFile = new File(aParentDir + aSubDir); if ( ! aSubFile.exists()) { return aSubFile.mkdirs
45、); } else { return true ; } } else { return false ; } } } H hhhhh漫步 | 漫步资源站 Asp教程.Net教程PHP教
46、程JSP教程数据库网页设计网络管理网站运作大杂烩 窗体顶端 Web 窗体底端 漫步统计系统2006个人版,降价了,每套仅需30元,详情请进... FreeMarker设计指南(1) JSP教程-Java技巧及代码 FreeMarker设计指南(1) 1、快速入门 (1)模板 + 数据模型 = 输出 l FreeMarker基于设计者和程序员是具有不同专业技能的不同个体的观念 l 他们是分工劳动的:设计者专注于表示——创建HTML文件、图片、W
47、eb页面的其它可视化方面;程序员创建系统,生成设计页面要显示的数据 l 经常会遇到的问题是:在Web页面(或其它类型的文档)中显示的信息在设计页面时是无效的,是基于动态数据的 l 在这里,你可以在HTML(或其它要输出的文本)中加入一些特定指令,FreeMarker会在输出页面给最终用户时,用适当的数据替代这些代码 l 下面是一个例子:
48、ody>
Our latest product: ${latestProduct.name}!