1 引入freemaker包
注意:选取最新jar包,否则可能会报错
2 创建 Configuration对象: tempConfiguration = new Configuration();
Configuration 对象主要是用来获取模板(Template)对象(或者说文件)
3 设置Configuration信息,如模板存放位置,字符编码等;
tempConfiguration.setClassForTemplateLoading(this.getClass(), "/");
tempConfiguration.setDefaultEncoding("utf-8");
常用有两种方式来设置模板存放位置:
setClassForTemplateLoading(this.getClass(), "/"); //JAVA源码中相对路径,这里是classpath
setServletContextForTemplateLoading.getServletContext(),"templates")//获取web工程中相对路径,这里获取的是WebContent下templates文件夹路径
注意:第一种设置方式适用于自动生成代码,多数用于在main函数中运行时设置模板路径;第二种适用于servlet或者web开发中,用于动态生成页面
4 获取Template对象:template= tempConfiguration.getTemplate("wzq.ftl")
注意:classpath路径下应该先有个wzq.ftl文件,否则找不到文件
5 设定需要向模板中添加的数据,这里使用map存放数据
Map root = new HashMap();
User user = new User();
user.setName("zhansan");
root.put("user",user);
6 根据模板生成数据:数据可以为文件,也可以为stream
下面贴出代码,代码中有部分来自网上,关键部分按自己的理解经过修改,共两种方式,一种是基于main方法,另一种是servlet,代码并不完整,希望为用过java或者servlet的朋友一个参考
一个JAVA文件对应一个FTL模板
基于main方法使用
JAVA部分
package example; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; public class FrermarkerXml { Template testfile; Map root; private void initData() { root = new HashMap(); User user = new User(); user.setName("root"); user.setPwd("root"); List<Address> addresses = new ArrayList<Address>(); for (int i = 0; i < 2; i++) { Address address = new Address(); address.setName("address_"+i); addresses.add(address); } Map<String, Address> keyadds = new HashMap<String, Address>(); for (int i = 0; i < 2; i++) { Address address = new Address(); address.setName("mapaddress_"+i); keyadds.put("keyadd_"+i, address); } user.setAdds(addresses); user.setKeyadds(keyadds); root.put("user", user); } private void init(){ try { Configuration tempConfiguration = new Configuration(); tempConfiguration.setClassicCompatible(true); tempConfiguration.setClassForTemplateLoading(this.getClass(), "/"); tempConfiguration.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); tempConfiguration.setNumberFormat(""); tempConfiguration.setDefaultEncoding("utf-8"); testfile = tempConfiguration.getTemplate("wzq_main.ftl"); } catch (IOException ex) { ex.printStackTrace(); } } public String toString(){ StringWriter sw = new StringWriter(); File file = new File("C:\\Apps\\wzq.xml"); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { testfile.process(root, new OutputStreamWriter(new FileOutputStream(file))); } catch (Exception ex) { ex.printStackTrace(); } return sw.toString(); } FrermarkerXml(){ init(); initData(); } public static void main(String[] args) { System.out.println(new FrermarkerXml().toString()); } }
wzq_main.ftl
<用户名>${user.name}</用户名> <密码>${user.pwd}</密码> <#list user.adds as add> <address> <地址>List对象address值:${add.name} </地址> </address> </#list> <#list user.keyadds?keys as addkey> <address> key:${addkey} value:${user.keyadds[addkey].name} </address> </#list>
JAVA部分
package examples; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class Hello extends HttpServlet{ private Configuration cfg; public void init(){ cfg = new Configuration(); cfg.setServletContextForTemplateLoading(getServletContext(),"templates"); // cfg.setClassForTemplateLoading(this.getClass(), "/"); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ Map root = new HashMap(); User user = new User(); user.setName("zhansan"); root.put("user",user); Template t =cfg.getTemplate("wzq_servlet.ftl"); response.setContentType("text/html; charset=" + t.getEncoding()); PrintWriter out = response.getWriter(); try{ t.process(root,out); }catch(TemplateException e){ e.printStackTrace(); } } }
wzq_servlet.ftl
<html> <head> <title>hello!</title> </head> <body> <h1>hello-classpath ${user.name}!</h1> </body> </html>
原文地址:http://blog.csdn.net/wangzhongquan_/article/details/46007709