zoukankan      html  css  js  c++  java
  • java工程中使用freemarker例子

    新建java project,引入freemarker.jar, 本工程是用的版本:freemarker-2.3.20 版本

    java工程目录如下:

    test.ftl文件

    Html代码  收藏代码
    1. name : ${name}  
    2. age : ${age}  

     test类

    Java代码  收藏代码
    1. package com.freemarker;  
    2.   
    3. import java.io.File;  
    4. import java.io.IOException;  
    5. import java.io.OutputStreamWriter;  
    6. import java.io.Writer;  
    7. import java.util.HashMap;  
    8. import java.util.Map;  
    9.   
    10. import freemarker.template.Configuration;  
    11. import freemarker.template.Template;  
    12. import freemarker.template.TemplateException;  
    13.   
    14. public class Test {  
    15.     public static void main(String[] args) throws IOException, TemplateException {  
    16.   
    17.         //1.创建配置实例Cofiguration  
    18.         Configuration cfg = new Configuration();  
    19.   
    20.         //2.设置模板文件目录  
    21.         //(1)src目录下的目录(template在src下)  
    22.         //cfg.setDirectoryForTemplateLoading(new File("src/template"));  
    23.         //(2)完整路径(template在src下)  
    24.         //cfg.setDirectoryForTemplateLoading(new File(  
    25.         //      "D:/cpic-env/workspace/javaFreemarker/src/template"));  
    26.         //cfg.setDirectoryForTemplateLoading(new File("src/template"));  
    27.         //(3)工程目录下的目录(template/main在工程下)--推荐  
    28.         cfg.setDirectoryForTemplateLoading(new File("template/main"));  
    29.         //cfg.setObjectWrapper(new DefaultObjectWrapper());  
    30.         //获取模板(template)  
    31.         Template template = cfg.getTemplate("test.ftl");  
    32.         //建立数据模型(Map)  
    33.         Map<String, String> root = new HashMap<String, String>();  
    34.         root.put("name", "cxl");  
    35.         root.put("age", "25");  
    36.         //获取输出流(指定到控制台(标准输出))  
    37.         Writer out = new OutputStreamWriter(System.out);  
    38.         //StringWriter out = new StringWriter();  
    39.         //System.out.println(out.toString());  
    40.         //数据与模板合并(数据+模板=输出)  
    41.         template.process(root, out);  
    42.         out.flush();  
    43.     }  
    44. }  

    运行结果:

    Java代码  收藏代码
    1. name : cxl  
    2. age : 25  

     
     

  • 相关阅读:
    Apache Common DbUtils
    Jackson 框架,轻易转换JSON
    Java数据库ResultSet转json实现
    java获得当前文件路径
    JSP基本面试的试题
    mysql优化方法积累
    linux数据盘分区以及格式化
    linux 数据盘和系统盘的查看
    配置Tomcat使用https协议(配置SSL协议)
    idea-java项目配置
  • 原文地址:https://www.cnblogs.com/telwanggs/p/5357883.html
Copyright © 2011-2022 走看看