Freemarker 是一款模板引擎,是一種基於模版產生靜態檔案的通用工具,它是為java程式員提供的一個開發包。以下介紹web應用如何使用freemarker產生靜態html。
操作前先引入freemarker的jar包,將freemarker的jar包放到WebContent/WEB-INF/lib 下 1.首先在web工程中建立一個包 com.test.ftl 用來存放模板檔案,再建立一個模板檔案 hello.ftl,填入如下內容
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body><div>${blog.blogType}<br>${blog.blogTitle_ch}<br>${blog.article}</div></body></html>
2. 編寫freemarker工具類
package com.test.freemaker;import java.io.File;import java.io.FileOutputStream;import com.google.common.base.Joiner;import com.test.entity.Blog;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.io.OutputStreamWriter;import java.io.OutputStream;import java.io.Writer;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Calendar;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;public class FreemakerUtil { private Date date = new Date(); private Calendar calendar = Calendar.getInstance(); public static String template="hello.ftl"; public Date getDate() { return date; } private Calendar getCalendar() { return calendar; } private String getTimeUrl() { SimpleDateFormat s=new SimpleDateFormat("yyyy/MM/dd/"); String curDate = s.format(getCalendar().getTime());// int year = getCalendar().get(Calendar.YEAR);// int month =getCalendar().get(Calendar.MONTH)+1;// int day = getCalendar().get(Calendar.DAY_OF_MONTH);// int hour = getCalendar().get(Calendar.HOUR_OF_DAY); return curDate;// return ""+year+"/"+month+"/"+day+"/";// return ""+year+"-"+month+"-"+day+" "+hour+":00"; } public Template geTemplate(String name) { try { Configuration cfg = new Configuration(); String templatePath = this.getClass().getClassLoader().getResource("/com/test/ftl").getPath(); cfg.setDefaultEncoding("UTF-8"); // 設定去哪裡讀取相應的ftl模板檔案 cfg.setClassForTemplateLoading(this.getClass(), "/com/test/ftl"); // 在模板檔案目錄中找到名稱為name的檔案 Template temp = cfg.getTemplate(name); return temp; }catch(Exception e) { e.printStackTrace(); return null; } } /*控制台輸出*/ public void print(String name,Map<String,Object> root) { try { // 通過Template可以將模板檔案輸出到相應的流 Template temp = this.geTemplate(name); temp.process(root, new PrintWriter(System.out)); }catch(Exception e) { e.printStackTrace(); } } /* 輸出html檔案*/ public void fprint(String name ,Map<String,Object> root,List<String> list) { FileWriter out = null; try { // 通過一個檔案輸出資料流,就可以寫到相應的檔案中,此處用的是絕對路徑 String url =getTimeUrl(); File file = new File("/public/"+url+list.get(0)+"/index.html"); if(!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } out = new FileWriter(file); Template temp = geTemplate(name); temp.process(root, out); }catch(Exception e) { e.printStackTrace(); }finally { try { if(out != null) { out.close(); } }catch(Exception e) { e.printStackTrace(); } } } public void fprint(String name,String path,Map<String,Object> root,String title) {// FileWriter out = null; Writer writer = null; try { // 通過一個檔案輸出資料流,就可以寫到相應的檔案中,此處用的是絕對路徑 String url =getTimeUrl(); File file = new File(path+url+title+"/index.html"); if(!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } writer=new OutputStreamWriter(new FileOutputStream(file), "UTF-8");// out = new FileWriter(file); Template temp = geTemplate(name); temp.process(root, writer); }catch(Exception e) { e.printStackTrace(); }finally { try { if(writer != null) { writer.close(); } }catch(Exception e) { e.printStackTrace(); } } }}
3. 編寫web控制器,代碼中已給出詳盡的說明。
@Controllerpublic class TestController1 { @RequestMapping("/test") public void test(Blog blog,HttpServletRequest request,HttpServletResponse response) { Configuration cfg=new Configuration(); //擷取模板路徑 String templatePath=this.getClass().getClassLoader().getResource("/com/test/ftl").getPath(); try { //配置模板路徑 cfg.setDirectoryForTemplateLoading(new File(templatePath)); cfg.setDefaultEncoding("UTF-8"); //擷取目標模板 Template template = cfg.getTemplate("hello.ftl"); //建立目標html檔案 File file=new File(request.getServletContext().getRealPath("/public/"+blog.getBlogTitle_ch()+".html")); //建立字元輸出資料流 Writer writer=new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); //map用來給模板傳遞資料,writer將模板內容寫入到上面建立的html檔案 template.process(map, writer); writer.flush(); writer.close(); } catch (IOException | TemplateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }}
4.建立實體類,用來存放提交資訊。
import java.io.Serializable;@SuppressWarnings("serial")public class Blog implements Serializable { private int blogId; private String blogTime; private String article; private String blogType; private String blogTitle_ch; private String blogTitle_en; private String time; public String getBlogTitle_ch() { return blogTitle_ch; } public void setBlogTitle_ch(String blogTitle_ch) { this.blogTitle_ch = blogTitle_ch; } public String getBlogTitle_en() { return blogTitle_en; } public void setBlogTitle_en(String blogTitle_en) { this.blogTitle_en = blogTitle_en; } public int getBlogId() { return blogId; } public void setBlogId(int blogId) { this.blogId = blogId; } public String getBlogTime() { return blogTime; } public void setBlogTime(String blogTime) { this.blogTime = blogTime; } public String getArticle() { return article; } public void setArticle(String article) { this.article = article; } public String getBlogType() { return blogType; } public void setBlogType(String blogType) { this.blogType = blogType; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
5.前端提交請求
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Test</title></head><body> <form id="form1" action="test" method="post"> 類型:<input type="text" name="blogType"><br> 題目:<input type="text" name="blogTitle_ch"><br> 內容:<textarea name="article"></textarea><br> <input type="submit" value="提交"> </form></body></html>
這樣,就完成了web項目使用freemarker產生靜態頁面的一個簡單例子。