数据模型是对象时如何利用freemarker生成静态文件

来源:互联网 发布:windows latex 配置 编辑:程序博客网 时间:2024/05/18 01:24

前面一篇文章数据模板是个map时展示了如何生成静态文件,如果数据模板里面的数据是一个对象时该如何写呢?

下面就展示一下这种情况下的代码是如何写的;

package com.neteae.web.test;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.Writer;import java.util.HashMap;import java.util.Map;import com.netease.web.model.User;import freemarker.template.Configuration;import freemarker.template.Template;public class FreemarkerModel {public static void main(String args[]){User user = new User();user.setName("小谢");Map<String,User> root = new HashMap<String,User>();root.put("user", user);Configuration cfg =  new Configuration();//Configuration读取模板文件try {cfg.setDirectoryForTemplateLoading(new File("WebContent/WEB-INF/ftl/test"));//制定模板文件的目录    Template template = cfg.getTemplate("freemarkermodel.ftl");//Template模板    Writer writer = new FileWriter(new File("freemarkermodel.html"));//产生的文件   template.process(root, writer);//将模板和数据产生文件   writer.flush();//将数据从缓存中清空;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

User对象:

package com.netease.web.model;public class User {public String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}

模板文件:

<html><head><title>测试下freemarker模板</title></head><body>你好,${user.name} </body></html>

执行程序:




0 0
原创粉丝点击