美文网首页
FreeMarker入门

FreeMarker入门

作者: Toconscience | 来源:发表于2017-04-11 23:47 被阅读382次

    这里有个系列博客很不错,应该是最合适的入门教程了。Java模板引擎FreeMarker系列
    这里的对FreeMarker的简介也很棒:使用Java对FreeMarker开发Web模板

    简介

    FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写,被主要用来生成HTML页面,特别是基于MVC模式的Web应用的页面。当然,FreeMarker同样可以应用于非Web应用程序环境。虽然FreeMarker具有一些编程的能力,但通常由Java程序准备要显示的数据,由FreeMarker模板显示准备的数据(如下图)

    overviewoverview

    FreeMarker不是一个Web应用框架,也与容器无关,因为它并不知道HTTP或者Servlet。它适合作为Model2框架(如Struts)的视图组件。FreeMarker模板也支持JSP标签库。

    Freemarker生成静态页面的过程是,模板引擎读取模板页面,解析其中的标签,完成指令相对应的操作,然后采用键值对的方式传递参数替换模板中的取值表达式,最后根据配置的路径生成一个新的静态页面。

    FreeMarker常用标签

    1. ${…}:取值标签。表示输出变量的内容。如:${name}可以取得root中key为name的值。${person.name}可以取得成员变量为person的name属性。
    2. <#…>:FTL指令(FreeMarker模板语言标记)如:<#if>表示判断、<#list>表示循环枚举、<#include>表示包含其他页面。
    3. <@…>:宏,自定义标签。
    4. 注释:包含在<#---->之间。

    第一个例子

    模板 + 数据模型 = 输出

    英文就是 template + data-model = output

    首先,创建模板如下:

    <html>
    <head>
      <title>Welcome!</title>
    </head>
    <body>
      <h1>Welcome ${user}!</h1>
      <p>Our latest product:
      <a href="${latestProduct.url}">${latestProduct.name}</a>!
    </body>
    </html>
    

    在程序端,只需要简单的四步:

    1. 得到Configuration类的实例。
    2. 创建data-model对象。
    3. 获取template文件。
    4. 把template和data-model捏合到一起产生输出。

    代码如下:
    首先创建data-model类:

    /**
     * Product bean; note that it must be a public class!
     */
    public class Product {
    
        private String url;
        private String name;
    
        // As per the JavaBeans spec., this defines the "url" bean property
        // It must be public!
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        // As per the JavaBean spec., this defines the "name" bean property
        // It must be public!
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    主函数:

    import freemarker.template.*;
    import java.util.*;
    import java.io.*;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            
            /* ------------------------------------------------------------------------ */    
            /* You should do this ONLY ONCE in the whole application life-cycle:        */    
        
            /* Create and adjust the configuration singleton */
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
            cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);
    
            /* ------------------------------------------------------------------------ */    
            /* You usually do these for MULTIPLE TIMES in the application life-cycle:   */    
    
            /* Create a data-model */
            Map root = new HashMap();
            root.put("user", "Big Joe");
            Product latest = new Product();
            latest.setUrl("products/greenmouse.html");
            latest.setName("green mouse");
            root.put("latestProduct", latest);
    
            /* Get the template (uses cache internally) */
            Template temp = cfg.getTemplate("test.ftlh");
    
            /* Merge data-model with template */
            Writer out = new OutputStreamWriter(System.out);
            temp.process(root, out);
            // Note: Depending on what `out` is, you may need to call `out.close()`.
            // This is usually the case for file output, but not for servlet output.
        }
    }
    

    可以看到,有了JSP的知识,FreeMarker还是很好学习的。更多的用法可以参考上面的博客以及官方教程。本篇到此为止。

    相关文章

      网友评论

          本文标题:FreeMarker入门

          本文链接:https://www.haomeiwen.com/subject/csjpattx.html