利用FreeMarker如何生成静态页面(转)

来源:互联网 发布:无主之地2mac汉化 编辑:程序博客网 时间:2024/05/20 22:36

众所周知,FreeMarker适合于作为Web应用的表现层,那么我们就把把页面中所需要的样式放入FreeMarker文件中,然后将页面所需要的数据动态绑定,并放入Map中,通过调用FreeMarker模板文件解析类process()方法完成静态页面的生成。了解了上面的原理,接下来我就一步步带您实现FreeMarker生成静态页面。

java代码(一)

package tool;  
 
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStreamWriter;  
import java.io.Writer;  
import java.util.Map;  
 
import freemarker.template.Configuration;  
import freemarker.template.DefaultObjectWrapper;  
import freemarker.template.Template;  
import freemarker.template.TemplateException;  
 
/******************************************************************************* 
 *  
 * @author wuzhenzhong 
 *  
 * @since Feb 5, 2010 
 *  
 ******************************************************************************/ 
public class FreeMarkertUtil {  
    /** 
     * templatePath模板文件存放路径,templateName 模板文件名称,filename 生成的文件名称 
     * @param templatePath 
     * @param templateName 
     * @param fileName 
     * @param root 
     */ 
    public static void analysisTemplate(String templatePath,  
            String templateName, String fileName, Map<?, ?> root) {  
        try {  
            //初使化FreeMarker配置  
            Configuration config = new Configuration();  
            // 设置要解析的模板所在的目录,并加载模板文件  
            config.setDirectoryForTemplateLoading(new File(templatePath));  
            // 设置包装器,并将对象包装为数据模型  
            config.setObjectWrapper(new DefaultObjectWrapper());  
 
            // 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致  
            // 否则会出现乱码  
            Template template = config.getTemplate(templateName, "UTF-8");  
            // 合并数据模型与模板  
            FileOutputStream fos = new FileOutputStream(fileName);  
            Writer out = new OutputStreamWriter(fos, "UTF-8");  
            template.process(root, out);  
            out.flush();  
            out.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (TemplateException e) {  
            e.printStackTrace();  
        }  
    }  
 

java代码(二)

package tool;  
 
/***************************************************** 
 *  
 * @author wuzhenzhong 
 *  
 * @since Feb 5, 2010  
 * 
 *****************************************************/ 
public class HtmlContent {  
    private String userName;  
    private String userPassword;  
    /** 
     * @return the userName 
     */ 
    public String getUserName() {  
        return userName;  
    }  
    /** 
     * @param userName the userName to set 
     */ 
    public void setUserName(String userName) {  
        this.userName = userName;  
    }  
    /** 
     * @return the userPassword 
     */ 
    public String getUserPassword() {  
        return userPassword;  
    }  
    /** 
     * @param userPassword the userPassword to set 
     */ 
    public void setUserPassword(String userPassword) {  
        this.userPassword = userPassword;  
    }  
 
 

java代码(三)

package tool;  
 
import java.util.HashMap;  
import java.util.Map;  
 
/******************************************************************************* 
 *  
 * @author wuzhenzhong 
 *  
 * @since Feb 5, 2010 
 *  
 ******************************************************************************/ 
public class CreateHtmlTest {  
    public static void main(String[] args) {  
        HtmlContent content = new HtmlContent();  
        content.setUserName("张三");  
        content.setUserPassword("123");  
 
        Map<String, Object> root = new HashMap<String, Object>();  
        root.put("content", content);  
        String templatesPath = "E:/templates";  
        String templateFile = "/createhtml.ftl";  
        String htmlFile = templatesPath + "/firsthtml.html";  
        FreeMarkertUtil.analysisTemplate(templatesPath, templateFile, htmlFile,  
                root);  
    }  

html代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>user.ftl</title> 
</head> 
  <body> 
    ${content.userName}  
    ${content.userPassword}  
  </body> 
</html> 

 下面在说一下FreeMarker的优缺点吧:

优点:

1、易学易用
我是看了一天文档就用得挺熟练了,freemarker文档写得太好了,例子丰富,照做一遍全都会了。

2、功能强大
比Velocity强大多了,还支持JSP Tag。不过最有意义的是macro功能,可以自定义常用的macro,实现页面常规操作的可复用性。

3、报错信息友好
很多应用服务器的JSP报错信息是无法定位到源代码行的。不过freemarker报错定位很准确,丝毫不差,而且信息丰富,一看就知道怎么回事(虽然那个黄黄的页面看起来让人难受) 带着这种兴奋的心情来研究freemarker,但是用它做了几个项目以后问题来了,而且是很讨厌的问题.下面我就来说说FreeMarker的这几大罪状. 

 

 

缺点:
缺点一:freemarker的变量必须有值,没有被赋值的变量就会抛出异常,那个黄黄的freemarker出错页面,真是让人看了太难过了。
freemarker的FAQ上面冠冕堂皇的说,未赋值的变量强制抛错可以杜绝很多潜在的错误,如缺失潜在的变量命名,或者其他变量错误。但是实际的效果是:带来的是非常大的编程麻烦,程序里面几乎所有可能出现空值的变量统统需要加上${xxx?if_exists},有些循环条件还需要写if判断,这样不但没有杜绝应该杜绝的错误,反而极大增加了编程的麻烦。

缺点二:freemarker的map限定key必须是string,其他数据类型竟然无法操作!这一点就不讲了,JavaEye上面已经有人抱怨过了。连Webwork的开发人员Pat Lightboy都在抱怨这一点。


缺点三:freemarker为了编程方便把不可序列化的东西往session里面放!
freemarker支持在页面里面直接操作Session,request等,例如${Session[...]},方便确实很方便,但是一旦需要做群集,就会报错。

原创粉丝点击