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

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

http://blog.csdn.net/xumengxing/article/details/14476007

 

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

  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  
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.5.jar
commons-logging-1.0.4.jar
ezmorph-1.0.6.jar
freemarker-2.3.13.jar
freemarker.jar
json-lib-2.4-jdk15.jar
ognl-2.6.11.jar
spring-core-2.0.8.jar
struts2-core-2.1.6.jar
xwork-2.1.2.jar

公共类: User.java代码如下

  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. }  
package com.hsinghsu.test.model;

public class User
{
    private int id;

    private String name;

    private int age;

    public String getName()
    {
        return name;
    }

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

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
    
}

UserDao.java 代码如下,用于生成模拟数据:

  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. }  
package com.hsinghsu.test.dao;

import java.util.ArrayList;
import java.util.List;

import com.hsinghsu.test.model.User;

public class UserDao
{
    public List<User> getUserList()
    {
        List<User> list = new ArrayList<User>();
        User user = null;
        for (int i = 0; i < 10; i++)
        {
            user = new User();
            user.setId(i);
            user.setName("name" + i);
            user.setAge(i + i);
            list.add(user);
        }
        
        return list;
    }

}

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

UserActionFTL.java Action代码如下:

  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. }  
package com.hsinghsu.test.action;

import java.util.List;

import com.hsinghsu.test.dao.UserDao;
import com.hsinghsu.test.model.User;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 通过struts配置文件直接渲染ftl
 * @author HsingHsu
 *
 */
public class UserActionFTL extends ActionSupport
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private List<User> uList;

    public String execute()
    {
        System.out.println("===begin");

        UserDao userDao = new UserDao();

        uList = userDao.getUserList();

        return SUCCESS;
    }

    public List<User> getuList()
    {
        return uList;
    }

    public void setuList(List<User> uList)
    {
        this.uList = uList;
    }

}

struts.xml配置文件如下:

  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>  
<?xml version="1.0" encoding="UTF-8" ?>
  <!DOCTYPE struts PUBLIC
      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
      "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="hsinghsu" extends="struts-default">

		<!-- 直接使用struts freemaker 将对象渲染到ftl中 -->
		<action name="userListFTL" class="com.hsinghsu.test.action.UserActionFTL">
			<result name="success" type="freemarker">/templates/userStrutsTemplate.ftl</result>
		</action>

	</package>
</struts>

userStrutsTemplate.ftl文件配置如下:

  1. <table style="text-align:center;FONT-SIZE: 11pt; WIDTH: 600px; FONT-FAMILY: 宋体; BORDER-COLLAPSE: collapse" borderColor=#3399ff cellSpacing=cellPadding=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>  
<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>   
    <tr>   
        <td><b>id</b></td>   
        <td><b>name</b></td>  
        <td><b>age</b></td>    
    </tr>
    <#list uList as user>   
    <tr>   
        <td>${user.id}</td>   
        <td>${user.name}</td>
        <td>${user.age}</td>
    </tr>
	</#list>
</table>

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

FTL2HtmlFlie.java 通过ftl生成html文件类代码如下:

  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. }  
package com.hsinghsu.test.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FTL2HtmlFlie
{
    /**
     * 
     * @param ftlPath ftl的路径
     * @param ftlName ftl的名称
     * @param htmlPath 要生成的html路径
     * @param htmlName 要生成的html名称
     * @param dataMap 需要渲染到ftl中的map数据
     * @return
     */
    public static boolean createHtmlFile(String ftlPath, String ftlName,
            String htmlPath, String htmlName, Map dataMap)
    {
        boolean result = false;

        // 创建Configuration对象
        Configuration cfg = new Configuration();
        // 设置FreeMarker的模版文件位置
        cfg.setServletContextForTemplateLoading(
                ServletActionContext.getServletContext(), ftlPath);
        cfg.setEncoding(Locale.getDefault(), "utf-8");

        // 创建Template对象
        Template template = null;
        try
        {
            template = cfg.getTemplate(ftlName);
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
        template.setEncoding("utf-8");

        String path = ServletActionContext.getServletContext().getRealPath("/");

        File dir = new File(path + htmlPath);
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        File fileName = new java.io.File(path + htmlPath + htmlName);
        System.out.println("html file:" + fileName.getPath());

        Writer writer = null;

        try
        {
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(fileName), "utf-8"));
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        try
        {
            // 生成静态页面
            template.process(dataMap, writer);
            result = true;
        }
        catch (TemplateException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        try
        {
            writer.flush();
            writer.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return result;
    }
}

UserActionHtmlFile.java Action代码如下:

  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. }  
package com.hsinghsu.test.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hsinghsu.test.dao.UserDao;
import com.hsinghsu.test.model.User;
import com.hsinghsu.test.util.FTL2HtmlFlie;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 生成html文件,返回html文件给前台
 * @author HsingHsu
 *
 */
public class UserActionHtmlFile extends ActionSupport
{
    /**
     * 
     */
    private static final long serialVersionUID = -16215231106028452L;

    private String returnURL;

    public String execute() throws Exception
    {
        UserDao userDao = new UserDao();
        List<User> uList = userDao.getUserList();

        Map<String, List<User>> dataMap = new HashMap<String, List<User>>();
        dataMap.put("userList", uList);

        String ftlPath = "/templates/";
        String ftlName = "htmlFileTemplate.ftl";
        String htmlPath = "/html/user/";
        String htmlName = "user.html";

        boolean result = FTL2HtmlFlie.createHtmlFile(ftlPath, ftlName,
                htmlPath, htmlName, dataMap);
        this.returnURL = htmlPath + htmlName;

        if (result)
        {
            return SUCCESS;
        }
        else
        {
            return ERROR;
        }

    }

    public String getReturnURL()
    {
        return returnURL;
    }

    public void setReturnURL(String returnURL)
    {
        this.returnURL = returnURL;
    }

}

struts.xml配置文件如下:

  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>  
<?xml version="1.0" encoding="UTF-8" ?>
  <!DOCTYPE struts PUBLIC
      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
      "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="hsinghsu" extends="struts-default">

		<!-- 通过ftl生成html文件返回给用户 -->
		<action name="userListHtmlFile" class="com.hsinghsu.test.action.UserActionHtmlFile">
			<result type="redirect">${returnURL}</result>
		</action>

	</package>
</struts>

htmlFileTemplate.ftl文件配置如下:

  1. <table style="text-align:center;FONT-SIZE: 11pt; WIDTH: 600px; FONT-FAMILY: 宋体; BORDER-COLLAPSE: collapse" borderColor=#3399ff cellSpacing=cellPadding=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>  
<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>   
    <tr>   
        <td><b>id</b></td>   
        <td><b>name</b></td>  
        <td><b>age</b></td>    
    </tr>
    <#list userList as user>   
    <tr>   
        <td>${user.id}</td>   
        <td>${user.name}</td>
        <td>${user.age}</td>
    </tr>
	</#list>
</table>

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

FTL2String.java 通过ftl生成html字符串类代码如下:

  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. }  
package com.hsinghsu.test.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 
 * @author HsingHsu
 * 
 */
public class FTL2String
{
    
    /**
     * 
     * @param ftlPath ftl的路径
     * @param ftlName ftl的名称
     * @param jsonDataString 需要渲染的json字符串
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public static String createHtmlString(String ftlPath, String ftlName,
            String jsonDataString) throws IOException, TemplateException
    {
        String resultString;

        // 创建Configuration对象
        Configuration cfg = new Configuration();
        // 设置FreeMarker的模版文件位置
        cfg.setServletContextForTemplateLoading(
                ServletActionContext.getServletContext(), ftlPath);
        cfg.setEncoding(Locale.getDefault(), "utf-8");

        // 创建Template对象
        Template template = null;
        template = cfg.getTemplate(ftlName);
        template.setEncoding("utf-8");

        Map<String, Object> context = new HashMap<String, Object>();
        // 将json字符串加入数据模型
        context.put("getData", jsonDataString);

        // 输出流
        StringWriter writer = new StringWriter();
        // 将数据和模型结合生成html
        template.process(context, writer);
        // 获得html
        resultString = writer.toString();

        writer.close();
        return resultString;
    }

}

UserActionHtmlString.java Action代码如下:

  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. }  
package com.hsinghsu.test.action;

import java.util.List;

import net.sf.json.JSONArray;

import com.hsinghsu.test.dao.UserDao;
import com.hsinghsu.test.model.User;
import com.hsinghsu.test.util.FTL2String;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 返回html流给前台
 * @author HsingHsu
 *
 */
public class UserActionHtmlString extends ActionSupport
{

    /**
     * 
     */
    private static final long serialVersionUID = 1006905813011288043L;

    public String execute() throws Exception
    {
        UserDao userDao = new UserDao();
        List<User> uList = userDao.getUserList();

        // String jsonString =
        // "{'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}]}";

        String jsonString = JSONArray.fromObject(uList).toString();
        // jsonString = JSONObject.fromObject(uList).toString();

        System.out.println("json:" + jsonString);
        // 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"}]

        String ftlPath = "/templates/";
        String ftlName = "htmlStringTemplate.ftl";

        String html = FTL2String.createHtmlString(ftlPath, ftlName, jsonString);
        System.out.println("html:" + html);

        return SUCCESS;
    }
}

struts.xml配置文件如下,注:用户可根据不同的业务请求,来将html流展现给用户

  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>  
<?xml version="1.0" encoding="UTF-8" ?>
  <!DOCTYPE struts PUBLIC
      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
      "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="hsinghsu" extends="struts-default">
		
		<!-- 通过ftl生成html流返回给用户 -->
		<action name="userListHtmlString" class="com.hsinghsu.test.action.UserActionHtmlString">
		</action>

	</package>
</struts>

htmlStringTemplate.ftl文件配置如下:

  1. <#assign data = getData?eval>  
  2. <table style="text-align:center;FONT-SIZE: 11pt; WIDTH: 600px; FONT-FAMILY: 宋体; BORDER-COLLAPSE: collapse" borderColor=#3399ff cellSpacing=cellPadding=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>  
posted @ 2017-08-23 10:50  sky20080101  阅读(388)  评论(0)    收藏  举报