生成html页面(转) - 夜半花开
生成html页面(转)
2013-12-02 00:01
夜半花开
阅读(2076)
评论(0)
编辑
收藏
举报
同学接到一个做网站美工的小项目,没有逻辑处理的页面和数据库操作,这样对于我们这种程序研发人员反而还比较棘手。。
上网搜了一下有没有偷懒的方法,发现了freemarker。。可以根据java代码生成html文件的好东东。
二话不说,下载源代码。freemarker-2.3.16.tar.gz,下了这个最新的版本。解压后,有了需要的jar包——-freemarker.jar。
先来看个小例子吧!在源码的examples文件里,找到一个模板文件Test.ftl。拷出来修改其为以下内容:
- <#macro greet person,website>
- Hello ${person}! Your Website is ${website}.
- </#macro>
- <html>
- <head>
- <title>Hello World</title>
- </head>
- <body>
- <@greet person=“Sfeve” website=“http://sfeve.iteye.com”/>
- </body>
- </html>
大家随便一看应该就能明白个八九成吧。。。
再写个Main函数测试一下!
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- import java.util.HashMap;
- import java.util.Map;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- public class Test {
- public static void main(String[] args) throws Exception {
- Configuration cfg = new Configuration();
- cfg.setDirectoryForTemplateLoading(new File(“bin”)); //设置读取模板文件的目录
- Template t = cfg.getTemplate(“Test.ftl”); //读取文件名为Test.ftl的模板
- Map root = new HashMap(); //存储数据
- Writer out = new OutputStreamWriter(new FileOutputStream(
- “Test.html”), “GBK”); //输出流
- t.process(root, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
- System.out.println(“Create successfully!”);
- }
- }
运行,即在当前文件目录下生成了名为Test.html的文件,其代码如下:
- <html>
- <head>
- <title>Hello World</title>
- </head>
- <body>
- Hello Sfeve! Your Website is <a href=“http://sfeve.iteye.com”>http://sfeve.iteye.com</a>.
- </body>
- </html>
很爽吧,更多精彩功能有待发掘。。。
PS:模板文件(这里是Test.ftl)一定要放到测试函数指定的目录里哦!否则会报找不到文件的异常。附件是源码和MyEclipse的freemarker插件。插件的使用方法就不磨叽了~