FreeMarker几种不同方式的展现数据

FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具。
本文主要写了3种方法通过freemarker与java对象数据结合,将数据展现于前台页面。

注:项目jar包
[plain]  view plain copy
  1. commons-beanutils-1.7.0.jar  
  2. commons-collections-3.1.jar  
  3. commons-fileupload-1.2.1.jar  
  4. commons-io-1.3.2.jar  
  5. commons-lang-2.5.jar  
  6. commons-logging-1.0.4.jar  
  7. ezmorph-1.0.6.jar  
  8. freemarker-2.3.13.jar  
  9. freemarker.jar  
  10. json-lib-2.4-jdk15.jar  
  11. ognl-2.6.11.jar  
  12. spring-core-2.0.8.jar  
  13. struts2-core-2.1.6.jar  
  14. xwork-2.1.2.jar  
公共类:
User.java代码如下
[java]  view plain copy
  1. package com.hsinghsu.test.model;  
  2.   
  3. public class User  
  4. {  
  5.     private int id;  
  6.   
  7.     private String name;  
  8.   
  9.     private int age;  
  10.   
  11.     public String getName()  
  12.     {  
  13.         return name;  
  14.     }  
  15.   
  16.     public void setName(String name)  
  17.     {  
  18.         this.name = name;  
  19.     }  
  20.   
  21.     public int getId()  
  22.     {  
  23.         return id;  
  24.     }  
  25.   
  26.     public void setId(int id)  
  27.     {  
  28.         this.id = id;  
  29.     }  
  30.   
  31.     public int getAge()  
  32.     {  
  33.         return age;  
  34.     }  
  35.   
  36.     public void setAge(int age)  
  37.     {  
  38.         this.age = age;  
  39.     }  
  40.       
  41. }  
UserDao.java 代码如下,用于生成模拟数据:
[java]  view plain copy
  1. package com.hsinghsu.test.dao;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import com.hsinghsu.test.model.User;  
  7.   
  8. public class UserDao  
  9. {  
  10.     public List<User> getUserList()  
  11.     {  
  12.         List<User> list = new ArrayList<User>();  
  13.         User user = null;  
  14.         for (int i = 0; i < 10; i++)  
  15.         {  
  16.             user = new User();  
  17.             user.setId(i);  
  18.             user.setName("name" + i);  
  19.             user.setAge(i + i);  
  20.             list.add(user);  
  21.         }  
  22.           
  23.         return list;  
  24.     }  
  25.   
  26. }  

1.使用struts配置文件直接将数据渲染到ftl中

UserActionFTL.java Action代码如下:
[java]  view plain copy
  1. package com.hsinghsu.test.action;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.hsinghsu.test.dao.UserDao;  
  6. import com.hsinghsu.test.model.User;  
  7. import com.opensymphony.xwork2.ActionSupport;  
  8.   
  9. /** 
  10.  * 通过struts配置文件直接渲染ftl 
  11.  * @author HsingHsu 
  12.  * 
  13.  */  
  14. public class UserActionFTL extends ActionSupport  
  15. {  
  16.     /** 
  17.      *  
  18.      */  
  19.     private static final long serialVersionUID = 1L;  
  20.   
  21.     private List<User> uList;  
  22.   
  23.     public String execute()  
  24.     {  
  25.         System.out.println("===begin");  
  26.   
  27.         UserDao userDao = new UserDao();  
  28.   
  29.         uList = userDao.getUserList();  
  30.   
  31.         return SUCCESS;  
  32.     }  
  33.   
  34.     public List<User> getuList()  
  35.     {  
  36.         return uList;  
  37.     }  
  38.   
  39.     public void setuList(List<User> uList)  
  40.     {  
  41.         this.uList = uList;  
  42.     }  
  43.   
  44. }  
struts.xml配置文件如下:
[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   <!DOCTYPE struts PUBLIC  
  3.       "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.       "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <package name="hsinghsu" extends="struts-default">  
  7.   
  8.         <!-- 直接使用struts freemaker 将对象渲染到ftl中 -->  
  9.         <action name="userListFTL" class="com.hsinghsu.test.action.UserActionFTL">  
  10.             <result name="success" type="freemarker">/templates/userStrutsTemplate.ftl</result>  
  11.         </action>  
  12.   
  13.     </package>  
  14. </struts>  
userStrutsTemplate.ftl文件配置如下:
[html]  view plain copy
  1. <table style="text-align:center;FONT-SIZE: 11pt; WIDTH: 600px; FONT-FAMILY: 宋体; BORDER-COLLAPSE: collapse" borderColor=#3399ff cellSpacing=0 cellPadding=0 align=center border=1>     
  2.     <tr>     
  3.         <td><b>id</b></td>     
  4.         <td><b>name</b></td>    
  5.         <td><b>age</b></td>      
  6.     </tr>  
  7.     <#list uList as user>     
  8.     <tr>     
  9.         <td>${user.id}</td>     
  10.         <td>${user.name}</td>  
  11.         <td>${user.age}</td>  
  12.     </tr>  
  13.     </#list>  
  14. </table>  

2.通过生成html文件,返回该html的url

FTL2HtmlFlie.java 通过ftl生成html文件类代码如下:
[java]  view plain copy
  1. package com.hsinghsu.test.util;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.OutputStreamWriter;  
  9. import java.io.UnsupportedEncodingException;  
  10. import java.io.Writer;  
  11. import java.util.Locale;  
  12. import java.util.Map;  
  13.   
  14. import org.apache.struts2.ServletActionContext;  
  15.   
  16. import freemarker.template.Configuration;  
  17. import freemarker.template.Template;  
  18. import freemarker.template.TemplateException;  
  19.   
  20. public class FTL2HtmlFlie  
  21. {  
  22.     /** 
  23.      *  
  24.      * @param ftlPath ftl的路径 
  25.      * @param ftlName ftl的名称 
  26.      * @param htmlPath 要生成的html路径 
  27.      * @param htmlName 要生成的html名称 
  28.      * @param dataMap 需要渲染到ftl中的map数据 
  29.      * @return 
  30.      */  
  31.     public static boolean createHtmlFile(String ftlPath, String ftlName,  
  32.             String htmlPath, String htmlName, Map dataMap)  
  33.     {  
  34.         boolean result = false;  
  35.   
  36.         // 创建Configuration对象  
  37.         Configuration cfg = new Configuration();  
  38.         // 设置FreeMarker的模版文件位置  
  39.         cfg.setServletContextForTemplateLoading(  
  40.                 ServletActionContext.getServletContext(), ftlPath);  
  41.         cfg.setEncoding(Locale.getDefault(), "utf-8");  
  42.   
  43.         // 创建Template对象  
  44.         Template template = null;  
  45.         try  
  46.         {  
  47.             template = cfg.getTemplate(ftlName);  
  48.         }  
  49.         catch (IOException e1)  
  50.         {  
  51.             e1.printStackTrace();  
  52.         }  
  53.         template.setEncoding("utf-8");  
  54.   
  55.         String path = ServletActionContext.getServletContext().getRealPath("/");  
  56.   
  57.         File dir = new File(path + htmlPath);  
  58.         if (!dir.exists())  
  59.         {  
  60.             dir.mkdirs();  
  61.         }  
  62.   
  63.         File fileName = new java.io.File(path + htmlPath + htmlName);  
  64.         System.out.println("html file:" + fileName.getPath());  
  65.   
  66.         Writer writer = null;  
  67.   
  68.         try  
  69.         {  
  70.             writer = new BufferedWriter(new OutputStreamWriter(  
  71.                     new FileOutputStream(fileName), "utf-8"));  
  72.         }  
  73.         catch (UnsupportedEncodingException e)  
  74.         {  
  75.             e.printStackTrace();  
  76.         }  
  77.         catch (FileNotFoundException e)  
  78.         {  
  79.             e.printStackTrace();  
  80.         }  
  81.         try  
  82.         {  
  83.             // 生成静态页面  
  84.             template.process(dataMap, writer);  
  85.             result = true;  
  86.         }  
  87.         catch (TemplateException e)  
  88.         {  
  89.             e.printStackTrace();  
  90.         }  
  91.         catch (IOException e)  
  92.         {  
  93.             e.printStackTrace();  
  94.         }  
  95.         try  
  96.         {  
  97.             writer.flush();  
  98.             writer.close();  
  99.         }  
  100.         catch (IOException e)  
  101.         {  
  102.             e.printStackTrace();  
  103.         }  
  104.   
  105.         return result;  
  106.     }  
  107. }  
UserActionHtmlFile.java Action代码如下:
[java]  view plain copy
  1. package com.hsinghsu.test.action;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import com.hsinghsu.test.dao.UserDao;  
  8. import com.hsinghsu.test.model.User;  
  9. import com.hsinghsu.test.util.FTL2HtmlFlie;  
  10. import com.opensymphony.xwork2.ActionSupport;  
  11.   
  12. /** 
  13.  * 生成html文件,返回html文件给前台 
  14.  * @author HsingHsu 
  15.  * 
  16.  */  
  17. public class UserActionHtmlFile extends ActionSupport  
  18. {  
  19.     /** 
  20.      *  
  21.      */  
  22.     private static final long serialVersionUID = -16215231106028452L;  
  23.   
  24.     private String returnURL;  
  25.   
  26.     public String execute() throws Exception  
  27.     {  
  28.         UserDao userDao = new UserDao();  
  29.         List<User> uList = userDao.getUserList();  
  30.   
  31.         Map<String, List<User>> dataMap = new HashMap<String, List<User>>();  
  32.         dataMap.put("userList", uList);  
  33.   
  34.         String ftlPath = "/templates/";  
  35.         String ftlName = "htmlFileTemplate.ftl";  
  36.         String htmlPath = "/html/user/";  
  37.         String htmlName = "user.html";  
  38.   
  39.         boolean result = FTL2HtmlFlie.createHtmlFile(ftlPath, ftlName,  
  40.                 htmlPath, htmlName, dataMap);  
  41.         this.returnURL = htmlPath + htmlName;  
  42.   
  43.         if (result)  
  44.         {  
  45.             return SUCCESS;  
  46.         }  
  47.         else  
  48.         {  
  49.             return ERROR;  
  50.         }  
  51.   
  52.     }  
  53.   
  54.     public String getReturnURL()  
  55.     {  
  56.         return returnURL;  
  57.     }  
  58.   
  59.     public void setReturnURL(String returnURL)  
  60.     {  
  61.         this.returnURL = returnURL;  
  62.     }  
  63.   
  64. }  
struts.xml配置文件如下:
[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   <!DOCTYPE struts PUBLIC  
  3.       "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.       "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <package name="hsinghsu" extends="struts-default">  
  7.   
  8.         <!-- 通过ftl生成html文件返回给用户 -->  
  9.         <action name="userListHtmlFile" class="com.hsinghsu.test.action.UserActionHtmlFile">  
  10.             <result type="redirect">${returnURL}</result>  
  11.         </action>  
  12.   
  13.     </package>  
  14. </struts>  
htmlFileTemplate.ftl文件配置如下:
[html]  view plain copy
  1. <table style="text-align:center;FONT-SIZE: 11pt; WIDTH: 600px; FONT-FAMILY: 宋体; BORDER-COLLAPSE: collapse" borderColor=#3399ff cellSpacing=0 cellPadding=0 align=center border=1>     
  2.     <tr>     
  3.         <td><b>id</b></td>     
  4.         <td><b>name</b></td>    
  5.         <td><b>age</b></td>      
  6.     </tr>  
  7.     <#list userList as user>     
  8.     <tr>     
  9.         <td>${user.id}</td>     
  10.         <td>${user.name}</td>  
  11.         <td>${user.age}</td>  
  12.     </tr>  
  13.     </#list>  
  14. </table>  

3.通过ftl生成html字符串流,将生成的html字符串返回给前台。

FTL2String.java 通过ftl生成html字符串类代码如下:
[java]  view plain copy
  1. package com.hsinghsu.test.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.StringWriter;  
  5. import java.util.HashMap;  
  6. import java.util.Locale;  
  7. import java.util.Map;  
  8.   
  9. import org.apache.struts2.ServletActionContext;  
  10.   
  11. import freemarker.template.Configuration;  
  12. import freemarker.template.Template;  
  13. import freemarker.template.TemplateException;  
  14.   
  15. /** 
  16.  *  
  17.  * @author HsingHsu 
  18.  *  
  19.  */  
  20. public class FTL2String  
  21. {  
  22.       
  23.     /** 
  24.      *  
  25.      * @param ftlPath ftl的路径 
  26.      * @param ftlName ftl的名称 
  27.      * @param jsonDataString 需要渲染的json字符串 
  28.      * @return 
  29.      * @throws IOException 
  30.      * @throws TemplateException 
  31.      */  
  32.     public static String createHtmlString(String ftlPath, String ftlName,  
  33.             String jsonDataString) throws IOException, TemplateException  
  34.     {  
  35.         String resultString;  
  36.   
  37.         // 创建Configuration对象  
  38.         Configuration cfg = new Configuration();  
  39.         // 设置FreeMarker的模版文件位置  
  40.         cfg.setServletContextForTemplateLoading(  
  41.                 ServletActionContext.getServletContext(), ftlPath);  
  42.         cfg.setEncoding(Locale.getDefault(), "utf-8");  
  43.   
  44.         // 创建Template对象  
  45.         Template template = null;  
  46.         template = cfg.getTemplate(ftlName);  
  47.         template.setEncoding("utf-8");  
  48.   
  49.         Map<String, Object> context = new HashMap<String, Object>();  
  50.         // 将json字符串加入数据模型  
  51.         context.put("getData", jsonDataString);  
  52.   
  53.         // 输出流  
  54.         StringWriter writer = new StringWriter();  
  55.         // 将数据和模型结合生成html  
  56.         template.process(context, writer);  
  57.         // 获得html  
  58.         resultString = writer.toString();  
  59.   
  60.         writer.close();  
  61.         return resultString;  
  62.     }  
  63.   
  64. }  
UserActionHtmlString.java Action代码如下:
[java]  view plain copy
  1. package com.hsinghsu.test.action;  
  2.   
  3. import java.util.List;  
  4.   
  5. import net.sf.json.JSONArray;  
  6.   
  7. import com.hsinghsu.test.dao.UserDao;  
  8. import com.hsinghsu.test.model.User;  
  9. import com.hsinghsu.test.util.FTL2String;  
  10. import com.opensymphony.xwork2.ActionSupport;  
  11.   
  12. /** 
  13.  * 返回html流给前台 
  14.  * @author HsingHsu 
  15.  * 
  16.  */  
  17. public class UserActionHtmlString extends ActionSupport  
  18. {  
  19.   
  20.     /** 
  21.      *  
  22.      */  
  23.     private static final long serialVersionUID = 1006905813011288043L;  
  24.   
  25.     public String execute() throws Exception  
  26.     {  
  27.         UserDao userDao = new UserDao();  
  28.         List<User> uList = userDao.getUserList();  
  29.   
  30.         // String jsonString =  
  31.         // "{'userList': [{'id': 0,'name': 'name0','age': 0},{'id': 1,'name': 'name1','age': 2},{'id': 2,'name': 'name2','age': 2},{'id': 3,'name': 'name3','age': 2},{'id': 4,'name': 'name4','age': 2},{'id': 5,'name': 'name5','age': 2},{'id': 6,'name': 'name6','age': 2},{'id': 7,'name': 'name7','age': 2},{'id': 8,'name': 'name8','age': 2},{'id': 9,'name': 'name1','age': 2}]}";  
  32.   
  33.         String jsonString = JSONArray.fromObject(uList).toString();  
  34.         // jsonString = JSONObject.fromObject(uList).toString();  
  35.   
  36.         System.out.println("json:" + jsonString);  
  37.         // print:[{"age":0,"id":0,"name":"name0"},{"age":2,"id":1,"name":"name1"},{"age":4,"id":2,"name":"name2"},{"age":6,"id":3,"name":"name3"},{"age":8,"id":4,"name":"name4"},{"age":10,"id":5,"name":"name5"},{"age":12,"id":6,"name":"name6"},{"age":14,"id":7,"name":"name7"},{"age":16,"id":8,"name":"name8"},{"age":18,"id":9,"name":"name9"}]  
  38.   
  39.         String ftlPath = "/templates/";  
  40.         String ftlName = "htmlStringTemplate.ftl";  
  41.   
  42.         String html = FTL2String.createHtmlString(ftlPath, ftlName, jsonString);  
  43.         System.out.println("html:" + html);  
  44.   
  45.         return SUCCESS;  
  46.     }  
  47. }  
struts.xml配置文件如下,注:用户可根据不同的业务请求,来将html流展现给用户
[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   <!DOCTYPE struts PUBLIC  
  3.       "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.       "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <package name="hsinghsu" extends="struts-default">  
  7.           
  8.         <!-- 通过ftl生成html流返回给用户 -->  
  9.         <action name="userListHtmlString" class="com.hsinghsu.test.action.UserActionHtmlString">  
  10.         </action>  
  11.   
  12.     </package>  
  13. </struts>  
htmlStringTemplate.ftl文件配置如下:
[html]  view plain copy
  1. <#assign data = getData?eval>  
  2. <table style="text-align:center;FONT-SIZE: 11pt; WIDTH: 600px; FONT-FAMILY: 宋体; BORDER-COLLAPSE: collapse" borderColor=#3399ff cellSpacing=0 cellPadding=0 align=center border=1>     
  3.     <tr>     
  4.         <td><b>id</b></td>     
  5.         <td><b>name</b></td>    
  6.         <td><b>age</b></td>      
  7.     </tr>  
  8.       
  9.     <#list data as user>     
  10.     <tr>     
  11.         <td>${user.id}</td>     
  12.         <td>${user.name}</td>  
  13.         <td>${user.age}</td>  
  14.     </tr>  
  15.     </#list>  
  16.       
  17.     <#-- 注:jsonString = "{'userList': [{'id':******  
  18.     <#list data.userList as user>     
  19.     <tr>     
  20.         <td>${user.id}</td>     
  21.         <td>${user.name}</td>  
  22.         <td>${user.age}</td>  
  23.     </tr>  
  24.     </#list>  
  25.     -->  
  26.       
  27. </table>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值