一、 FreeMarker生成静态页原理 众所周知,FreeMarker适合于作为Web应用的表现层,那么我们就把把页面中所需要的样式放入FreeMarker文件中,然后将页面所需要的数据动态绑定,并放入Map中,通过调用FreeMarker模板文件解析类process()方法完成静态页面的生成。了解了上面的原理,接下来四夕就一步步带您实现FreeMarker生成静态页面。
<head> <title>生成html静态页面</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"; charset=UTF-8" /> </head> <body> <span>生成题干ID${question.id}</span> <span>生成题干内容${question.quesContent}</span> </body>
package com.itstyle.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.itstyle.model.Question; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; /** * * @author 科帮网(www.52itstyle.com) * */ public class CreatHtml { public static void CreatAllHtml(HttpServletRequest request){ Map<String,Object> root = new HashMap<String,Object>(); String path = request.getSession().getServletContext().getContextPath(); String templatePath = request.getSession().getServletContext().getRealPath("/file"); String templateName = "question.flt"; String targetHtmlPath =request.getSession().getServletContext().getRealPath("/file") +Constants.SF_FILE_SEPARATOR+"question.html"; Question question = new Question(1,"我是中国人"); root.put("question", question); root.put("path" , path); crateHTML(root, templatePath, templateName, targetHtmlPath); }
Configuration freemarkerCfg = new Configuration(); //加载模版 Writer out = null; try { //设置要解析的模板所在的目录,并加载模板文件 freemarkerCfg.setDirectoryForTemplateLoading(new File(templatePath)); //设置包装器,并将对象包装为数据模型 freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper()); //指定模版路径 Template template = freemarkerCfg.getTemplate(templateName,"UTF-8"); template.setEncoding("UTF-8"); //静态页面路径 FileOutputStream fos = new FileOutputStream(targetHtmlPath); out = new OutputStreamWriter(fos,"UTF-8"); //合并数据模型与模板 template.process(data, out); } catch (Exception e) { e.printStackTrace(); }finally{ try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
四、 创建FreeMarker模板文件动态绑定的数据对象类Question.java(实体类)
/** * * @author 科帮网(www.52itstyle.com) * */ public class Question { private Integer id; private String quesContent; public Question() { super(); } public Question(Integer id, String quesContent) { super(); this.id = id; this.quesContent = quesContent; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getQuesContent() { return quesContent; } public void setQuesContent(String quesContent) { this.quesContent = quesContent; } }
|
FreeMarker教你如何生成html静态页面源码
最新推荐文章于 2024-08-08 22:02:23 发布