freemarker 入门

编写一个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> 

你可能感兴趣的:(html,jsp,freemarker,cache,sun)