一、模板文件(ftl文件)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>查看文章: ${newsitem.title}</title> <script src="../../common/js/jquery.js" type="text/javascript"></script> <script type="text/javascript" src="../../common/js/base.js"></script> <script> function getValue(){ $.ajax({ type : "post", url : "../../TestServlet?action=getValue", data : null, success:function(msg){ alert(msg); } }) } </script> </head> <body> <input type="button" value="生成静态文件" onClick="getValue()" /> <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.publishDate} ) </td> <td align="right"> <a 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.content} </td> </tr> </table> <br> </td> </tr> </table> </body> </html>
?
二、servlet业务逻辑代码
public void getValue(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FreeMarkerTest freeMarkerTest = new FreeMarkerTest(); String path = request.getRealPath("/"); String fileName = getNewFileName(); boolean b = freeMarkerTest.createStaticHtml(path,fileName); response.getWriter().print(b); }
?
/** * 生成新文件名称(年月日时分秒+二位随机码) * * @return */ public String getNewFileName() { String newFileName = ""; Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyyMMddHHmmss"); newFileName = simpleDateFormat.format(date); String random = getRandom(2); return newFileName + random; } /** * 获取n位随机数 * * @param n * @return */ public String getRandom(int n) { String randomString = ""; if (n == 1) { randomString = (int) (Math.random() * 10) + ""; } else { randomString = getRandom(n - 1) + (int) (Math.random() * 10); } return randomString; }
?
三、dao 层核心代码
import java.io.*; import java.util.HashMap; import java.util.Map; import freemarker.template.*; /** * FreeMarker * @author Administrator * @data Mar 27, 2012 */ public class FreeMarkerTest { private Configuration freemarker_cfg = null; public boolean createStaticHtml(String path,String fileName) { NewsItem aItem = new NewsItem(); aItem.setTitle("新闻信息一"); aItem.setAuthor("administrator"); aItem.setHotNum("1000"); aItem.setPublishDate("2012-03-20"); aItem.setContent("新闻信息内容%%%%"); FreeMarkerTest test = new FreeMarkerTest(); Map root = new HashMap(); root.put("newsitem", aItem); String sGeneFilePath = "/"; boolean bOK = test.geneHtmlFile("view.ftl", root, sGeneFilePath, fileName+".htm",path); return bOK; } /** * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取. */ protected Configuration getFreeMarkerCFG(String path) { if (null == freemarker_cfg) { freemarker_cfg = new Configuration(); try { freemarker_cfg.setDirectoryForTemplateLoading(new File(path)); } catch (IOException e) { e.printStackTrace(); } } return freemarker_cfg; } /** * 生成静态文件. * * @param templateFileName * @param propMap * @param htmlFilePath * 要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/" * @param htmlFileName * 要生成的文件名,例如 "1.htm" */ public boolean geneHtmlFile(String templateFileName, Map propMap, String htmlFilePath, String htmlFileName,String path) { // @todo 从配置中取得要静态文件存放的根路径:需要改为自己的属性类调用 String sRootDir = path + "/modules/news/";//保存文件路径 Writer out = null; try { path = path + "WEB-INF/FTL/";//ftl路径 Template t = getFreeMarkerCFG(path).getTemplate(templateFileName); t.setEncoding("UTF-8"); // 如果根路径存在,则递归创建子目录 creatDirs(sRootDir, htmlFilePath); File afile = new File(sRootDir + "/" + htmlFilePath + "/" + htmlFileName); out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(afile),"UTF-8")); t.process(propMap, out); } catch (TemplateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally{ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 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; } } }
?