Freemarker应用案例

来源:互联网 发布:网络重生txt全集下载 编辑:程序博客网 时间:2024/05/17 04:37
package entity;public class User {private String name;private String passwd;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPasswd() {return passwd;}public void setPasswd(String passwd) {this.passwd = passwd;}}
核心代码:
package utit;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.DefaultObjectWrapper;import freemarker.template.Template;import freemarker.template.TemplateException;public class FreeMarkertUtil {/** * templatePath模板文件存放路径,templateName 模板文件名称,filename 生成的文件名称 * @param templatePath * @param templateName * @param fileName * @param root */public static void analysisTemplate(String templatePath,String templateName, String fileName, Map<?, ?> root) {try {//初使化FreeMarker配置Configuration config = new Configuration();// 设置要解析的模板所在的目录,并加载模板文件config.setDirectoryForTemplateLoading(new File(templatePath));// 设置包装器,并将对象包装为数据模型config.setObjectWrapper(new DefaultObjectWrapper());// 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致// 否则会出现乱码Template template = config.getTemplate(templateName, "UTF-8");// 合并数据模型与模板FileOutputStream fos = new FileOutputStream(fileName);Writer out = new OutputStreamWriter(fos, "UTF-8");template.process(root, out);out.flush();out.close();} catch (IOException e) {e.printStackTrace();} catch (TemplateException e) {e.printStackTrace();}}}

调用:

package client;import java.util.HashMap;import java.util.Map;import utit.FreeMarkertUtil;import entity.User;public class CreateHtml {public static void main(String[] args) {User user = new User();user.setName("张三");user.setPasswd("000");Map<String, Object> root = new HashMap<String, Object>();root.put("user", user);String templatesPath = "D:/JAVA/MyEclipse/myeclipse.10/Workspaces/MyEclipse 10/createHtml/WebRoot/WEB-INF/";String templateFile = "staticHtml.ftl";String htmlFile = templatesPath + "userhtml.html";FreeMarkertUtil.analysisTemplate(templatesPath, templateFile, htmlFile,root);}}

ftl文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>user.ftl</title></head>  <body>用户名:${user.name}<br/>密码:${user.passwd}  </body></html>

Freemarker-jar包

Freemarker下载

0 0