freemarker 入門

zk1878發表於2011-06-12

編寫一個ftl檔案如下

 

 <%@ page language="java" pageEncoding="GBK" contentType="text/html;charset=GBK"%>  
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>      
    <title>My JSP 'index.jsp' starting page</title>  
 <meta http-equiv="pragma" content="no-cache">  
 <meta http-equiv="cache-control" content="no-cache">  
 <meta http-equiv="expires" content="0">      
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
 <meta http-equiv="description" content="This is my page">  
  </head>  
  <body>  
   The first test: ${persion.name}  
  </body>  
</html>  

 

寫一個entity

public class User {
	String name;
	public User(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

 

用freemarker生成html檔案

public class Test {  
  
 public static void main(String[] args) throws Exception{  
  //模板路徑  
  String dir ="E:/e/";  
  Configuration cfg = new Configuration();   
  
  //載入freemarker模板檔案   
  cfg.setDirectoryForTemplateLoading(new File(dir));   
     
  //設定物件包裝器   
  cfg.setObjectWrapper(new DefaultObjectWrapper());   
     
  //設計異常處理器   
  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);   
     
  //定義並設定資料   
  Map<String, User> data = new HashMap<String, User>();   
  data.put("persion", new User("zhang san"));   
     
  //獲取指定模板檔案   
  Template template = cfg.getTemplate(dir+"test.ftl");   
     
  //定義輸入檔案,預設生成在工程根目錄   
  Writer out = new OutputStreamWriter(new FileOutputStream(dir+"test.html"),"GBK");   
     
  //最後開始生成   
  template.process(data, out);   
     
  System.out.println("successful");   
 
 
 }  
}  

 

執行以上程式碼將在E:/e/test.html,檔案內容如下

 <%@ page language="java" pageEncoding="GBK" contentType="text/html;charset=GBK"%> 
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head>     
    <title>My JSP 'index.jsp' starting page</title> 
 <meta http-equiv="pragma" content="no-cache"> 
 <meta http-equiv="cache-control" content="no-cache"> 
 <meta http-equiv="expires" content="0">     
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
 <meta http-equiv="description" content="This is my page"> 
  </head> 
  <body> 
   The first test: zhang san 
  </body> 
</html> 

相關文章