18910140161

生成html页面(转) - 夜半花开

顺晟科技

2022-09-15 19:58:26

106

生成html页面(转)

2013-12-02 00:01  夜半花开  阅读(2076)  评论(0)  编辑  收藏  举报

同学接到一个做网站美工的小项目,没有逻辑处理的页面和数据库操作,这样对于我们这种程序研发人员反而还比较棘手。。

 

上网搜了一下有没有偷懒的方法,发现了freemarker。。可以根据java代码生成html文件的好东东。

 

二话不说,下载源代码。freemarker-2.3.16.tar.gz,下了这个最新的版本。解压后,有了需要的jar包-------freemarker.jar。

 

先来看个小例子吧!在源码的examples文件里,找到一个模板文件Test.ftl。拷出来修改其为以下内容:

 

Ftl代码  收藏代码
  1. <#macro greet person,website>  
  2.    Hello ${person}! Your Website is ${website}.  
  3. </#macro>   
  4.     
  5. <html>     
  6. <head>     
  7. <title>Hello World</title>  
  8. </head>   
  9.     
  10. <body>     
  11. <@greet person="Sfeve" website="http://sfeve.iteye.com"/>     
  12. </body>     
  13. </html>   

 

 大家随便一看应该就能明白个八九成吧。。。

 

再写个Main函数测试一下!

 

Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.OutputStreamWriter;  
  4. import java.io.Writer;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7.   
  8. import freemarker.template.Configuration;  
  9. import freemarker.template.Template;  
  10.   
  11. public class Test {  
  12.     public static void main(String[] args) throws Exception {  
  13.         Configuration cfg = new Configuration();  
  14.           
  15.         cfg.setDirectoryForTemplateLoading(new File("bin"));  //设置读取模板文件的目录  
  16.           
  17.         Template t = cfg.getTemplate("Test.ftl");  //读取文件名为Test.ftl的模板  
  18.           
  19.         Map root = new HashMap();  //存储数据  
  20.           
  21.         Writer out = new OutputStreamWriter(new FileOutputStream(  
  22.                 "Test.html"), "GBK");  //输出流  
  23.           
  24.         t.process(root, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。  
  25.           
  26.         System.out.println("Create successfully!");  
  27.     }  
  28. }  

 

运行,即在当前文件目录下生成了名为Test.html的文件,其代码如下:

 

 

Html代码  收藏代码
  1. <html>     
  2. <head>     
  3. <title>Hello World</title>  
  4. </head>   
  5.     
  6. <body>     
  7.    Hello Sfeve! Your Website is <a href="http://sfeve.iteye.com">http://sfeve.iteye.com</a>.     
  8. </body>     
  9. </html>   

 

很爽吧,更多精彩功能有待发掘。。。

 

PS:模板文件(这里是Test.ftl)一定要放到测试函数指定的目录里哦!否则会报找不到文件的异常。附件是源码和MyEclipse的freemarker插件。插件的使用方法就不磨叽了~

我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航