freemaker示例

第一步  创建一个User.java文件 来两个变量

      public class User {
      private String userName;
 
      private String userPassword;

      //。。。这里省略set()  get()方法一定要加上;

      }

第二步  创建一个user.ftl文件 模板 先放在web目录下吧

       <!DOCTYPE>  
       <html>  
        <head>  
       <meta http-equiv=Content-Type content="text/html; charset=utf-8">  
       <title>user.ftl</title>  
        </head>  
       <body>  
         ${user.userName}  
         ${user.userPassword}  
       </body>  
     </html>

 第三步  创建一个FreemarkerUtil.java 工具类 

        //templatePath模板文件存放路径  
        //templateName 模板文件名称  
        //fileName 生成的文件名称 
        //templateEncoding 文本HTML的编码方式

        //Map<?, ?> root 储存的数据
       public class FreeMarkerUtil {
       public static void analysisTemplate(String templatePath,String                                 templateName,String fileName,String templateEncoding,                                         Map<?,?> root) {
       try {
      // 创建Configuration对象
      Configuration config=new Configuration();
      // 指定模板路径
      File file=new File(templatePath);
     //设置要解析的模板所在的目录,并加载模板文件
     config.setDirectoryForTemplateLoading(file);
     //设置包装器,并将对象包装为数据模型 
     config.setObjectWrapper(new DefaultObjectWrapper());
    //获取模板,并设置编码方式,编码必须要与页面中的编码格式一致 
   Template template =                                                                 config.getTemplate(templateName,templateEncoding);
    // 合并数据模型与模板
    FileOutputStream fos = new FileOutputStream(fileName);  
    //输出到页面
    Writer out = new OutputStreamWriter(fos,templateEncoding);  
       template.process(root, out);
         out.flush();
         out.close();
     } catch (IOException e) {
           e.printStackTrace();
       } catch (TemplateException e) {
    e.printStackTrace();
     }
   }
}

第四步  创建一个Test.java 测试类

    public class Test {
     public static void main(String[] args) {
     User user =new User();
     user.setUserName("测12312");
     user.setUserPassword("123");
     Map<String,Object> root=new HashMap<String,Object>();
    root.put("user", user);

    String fileName="user.ftl"; 
    String templatesPath="web";  
    String htmlFile=templatesPath+"/user.html"; 

    String templateEncoding="UTF-8";

     //这里的编码方式是为了以后可能还要输入韩文或者日文等信息为了灵活//也可以在工具类中写死一种
    FreeMarkerUtil.analysisTemplate(templatesPath, fileName,                     htmlFile,templateEncoding, root);
}
}

猜你喜欢

转载自www.cnblogs.com/stormy/p/9705664.html