Beetl实现静态页面生成

来源:互联网 发布:appstore日本福利软件 编辑:程序博客网 时间:2024/05/20 22:38

使用Beetl实现静态页生成

使用Beetl 1.1实现静态页的生成。 
使用struts1.2 
首先在Lisener中设置ServletGroupTemplate相关配置。 
模版文件位于WEB-INF/template下 
查看文本打印?
  1. public class InitLisener implements ServletContextListener{  
  2.     static Log log = LogFactory.getLog(InitLisener.class);  
  3.       
  4.     public void contextDestroyed(ServletContextEvent arg0) {  
  5.         ActionServletContext.destroyed();  
  6.     }  
  7.   
  8.     public void contextInitialized(ServletContextEvent event) {  
  9.         log.info("加载资源文件");  
  10.         ServletContext context = event.getServletContext();  
  11.         String configPath = context.getRealPath("//");  
  12.         ServletGroupTemplate.intance().init(context);  
  13.         ServletGroupTemplate.intance().getGroup().config("<!--:""-->""${""}");  
  14.         ServletGroupTemplate.intance().getGroup().setCharset("UTF-8");  
  15.         ServletGroupTemplate.intance().getGroup().registerFunction("fn.substring",new SubStringFunction());  
  16.         ServletGroupTemplate.intance().getGroup().registerFunction("fn.length",new LengthFunction());  
  17.           
  18.         //context.setAttribute("templatepath", context.getRealPath("WEB-INF/template"));  
  19.         System.out.println(context.getRealPath("WEB-INF/template"));  
  20.           
  21.         ActionServletContext.setServletContext(context);  
  22.         //PropertiesUtil.loadConfig();  
  23.     }  
  24.   
  25. }  


Action类,其中模拟了一些数据,输出路径为跟路径,文件名为index.html 
查看文本打印?
  1. public class StaticPageAction extends Action {  
  2.     /* 
  3.      * Generated Methods 
  4.      */  
  5.   
  6.     /** 
  7.      * Method execute 
  8.      *  
  9.      * @param mapping 
  10.      * @param form 
  11.      * @param request 
  12.      * @param response 
  13.      * @return ActionForward 
  14.      */  
  15.     public ActionForward execute(ActionMapping mapping, ActionForm form,  
  16.             HttpServletRequest request, HttpServletResponse response) {  
  17.         PrintWriter pWriter = null;  
  18.         ActionForward forward = new ActionForward();  
  19.         response.setCharacterEncoding("UTF-8");  
  20.           
  21.         String templatePath = (String) ActionServletContext.getServletContext()  
  22.                 .getAttribute("templatepath");  
  23.         String rootpath = ActionServletContext.getServletContext().getRealPath(  
  24.                 "/");  
  25.         rootpath = rootpath + "/index.html";  
  26.           
  27.         List<Channel> channelList = getNewsData();  
  28.         try {  
  29.             pWriter = response.getWriter();  
  30.             Template template = ServletGroupTemplate.intance().getTemplate(  
  31.                     "/index.html", request, response);  
  32.             template.set("channelList", channelList);  
  33.             template.set("user""chenlei");  
  34.             template.set("Chal"new Channel(1"栏目test""栏目说明"01030));  
  35.   
  36.             StringWriter writer = new StringWriter();  
  37.             template.getText(writer);  
  38.             // false为从文件开始处写入  
  39.             OutputStreamWriter outWriter = new OutputStreamWriter(  
  40.                     new FileOutputStream(rootpath, false), "UTF-8");  
  41.             System.out.println(writer.toString());  
  42.   
  43.             Writer out = new BufferedWriter(outWriter);  
  44.             out.write(writer.toString());  
  45.             out.flush();  
  46.             out.close();  
  47.   
  48.             pWriter.print("输出首页成功!<a href='index.jsp'>返回</>");  
  49.         } catch (IOException e) {  
  50.             pWriter.print("输出首页失败!");  
  51.         } catch (BeeException e) {  
  52.             // e.printStackTrace();  
  53.         }  
  54.   
  55.         return null;  
  56.     }  
  57.   
  58.     private List<Channel> getNewsData() {  
  59.   
  60.         List<Channel> newList = new ArrayList<Channel>(20);  
  61.         for (int i = 1; i <= 10; i++) {  
  62.             Channel chnnel = new Channel(i, "栏目" + i, "栏目说明" + i, 01030);  
  63.             for (int j = 1; j <= 11; j++) {  
  64.                 News news = new News(  
  65.                         j + i,  
  66.                         "新闻消息" + j + i,  
  67.                         "新华社消息: 控制语句占位符号是/<!--: ,这样,尽可能然模板少破坏原有文件,你可以通过浏览器直接浏览模板文件",  
  68.                         new Date(), "chnnal/news/" + j + i + "html");  
  69.                 news.setChannelId(i);  
  70.                 news.setChannelTitle(chnnel.getChnnelTitle());  
  71.                 chnnel.addNewsList(news);  
  72.             }  
  73.             newList.add(chnnel);  
  74.         }  
  75.         return newList;  
  76.     }  
  77. }  


模版文件:index.html 
查看文本打印?
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  2. <html>  
  3.   <head>  
  4.     <title>Index.html</title>  
  5.       
  6.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  7.     <meta http-equiv="description" content="this is my page">  
  8.     <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  9.   
  10.   </head>  
  11.     
  12.   <body>  
  13.   <!--:if(user!=null){  -->  
  14.     你好!${user}<br>  
  15.     ${Chal.chnnelTitle}  
  16.     ${channelList.~size}  
  17.   <!--:}  -->  
  18.     栏目列表  
  19.       
  20.    <div>  
  21.      
  22.    <!--: if(channelList.~size!=0){  
  23.       for(Channel in channelList){  -->  
  24.    <span >  
  25. <br>web.xml中的配置  
  26. <br><pre name="code" class="java"><?xml version="1.0" encoding="UTF-8"?>  
  27. <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  28.   <listener>  
  29.     <listener-class>com.otos.cl.common.listerner.InitLisener</listener-class>  
  30.   </listener>  
  31.   <context-param>  
  32. <param-name>GroupTemplate.Root</param-name>  
  33. <param-value>/WEB-INF/template</param-value>  
  34. </context-param>  
  35. <context-param>  
  36. <param-name>GroupTemplate.Optimize</param-name>  
  37. <param-value>true</param-value>  
  38. </context-param>  
  39. <context-param>  
  40. <param-name>GroupTemplate.NativeCall</param-name>  
  41. <param-value>true</param-value>  
  42. </context-param>  
  43. <context-param>  
  44. <param-name>GroupTemplate.Check</param-name>  
  45. <param-value>2</param-value>  
  46. </context-param>  
  47.   <filter>  
  48.     <filter-name>encode</filter-name>  
  49.     <filter-class>com.otos.cl.common.filter.FilterEncoding</filter-class>  
  50.     <init-param>  
  51.       <param-name>encoding</param-name>  
  52.       <param-value>utf-8</param-value>  
  53.     </init-param>  
  54.   </filter>  
  55.   <filter-mapping>  
  56.     <filter-name>encode</filter-name>  
  57.     <url-pattern>/*</url-pattern> 
  58.   </filter-mapping> 
  59.   <servlet> 
  60.     <servlet-name>act</servlet-name> 
  61.     <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> 
  62.     <init-param> 
  63.       <param-name>config</param-name> 
  64.       <param-value>/WEB-INF/struts-config.xml</param-value> 
  65.     </init-param> 
  66.     <init-param> 
  67.       <param-name>debug</param-name> 
  68.       <param-value>3</param-value> 
  69.     </init-param> 
  70.     <init-param> 
  71.       <param-name>detail</param-name> 
  72.       <param-value>3</param-value> 
  73.     </init-param> 
  74.     <load-on-startup>0</load-on-startup> 
  75.   </servlet> 
  76.   <servlet-mapping> 
  77.     <servlet-name>act</servlet-name> 
  78.     <url-pattern>*.do</url-pattern> 
  79.   </servlet-mapping> 
  80.   <welcome-file-list> 
  81.     <welcome-file>index.html</welcome-file> 
  82.     <welcome-file>index.jsp</welcome-file> 
  83.      
  84.   </welcome-file-list> 
  85. </web-app> 
  86. </pre> 
  87. <br>由于要对显示的字符串进行截取,定义了两个函数: 
  88. <br><pre name="code" class="java">/** 
  89.  * 用于在模版中截取字符串长度的函数 
  90.  *  
  91.  * @author chenl 
  92.  *  
  93.  */  
  94. public class SubStringFunction implements Function {  
  95.   
  96.     public Object call(Object[] objects, Context ctx) {  
  97.         String parentStr = "";  
  98.         Integer start = 0;  
  99.         Integer end = 0;  
  100.         Object str = objects[0];  
  101.         if (str == null) {  
  102.             return "";  
  103.         } else {  
  104.             parentStr = String.valueOf(str);  
  105.         }  
  106.   
  107.         Object startindex = objects[1];  
  108.         if (startindex == null) {  
  109.             return "";  
  110.         } else {  
  111.             start = Integer.valueOf(startindex.toString());  
  112.         }  
  113.         if (objects.length >= 3) {  
  114.             Object endindex = objects[2];  
  115.             if (endindex != null) {  
  116.                 end = Integer.valueOf(endindex.toString());  
  117.             }  
  118.         }  
  119.         if (start < 0 || end < 0) {  
  120.             throw new IllegalStateException("SubString函数中参数startindex和endindex不能小于0");  
  121.         }  
  122.   
  123.         int length = parentStr.length();  
  124.   
  125.         if (length == 1) {  
  126.             return parentStr;  
  127.         } else {  
  128.             if (end == 0)  
  129.                 parentStr = parentStr.substring(start);  
  130.             else  
  131.                 parentStr = parentStr.substring(start, end);  
  132.         }  
  133.   
  134.         return parentStr;  
  135.     }  
  136. }  
  137. </pre>  
  138. <br>  
  139. <br><pre name="code" class="java">/** 
  140.  * Beetl自定义函数 
  141.  * @author chenl 
  142.  * 
  143.  */  
  144. public class LengthFunction implements Function {  
  145.   
  146.     public Object call(Object[] arg0, Context arg1) {  
  147.         int length = 0;  
  148.         if(arg0.length==1){  
  149.             Object obj = arg0[0];  
  150.             if(obj instanceof String) {  
  151.                 length = ((String) obj).length();  
  152.             }else if(obj instanceof Integer){  
  153.                 length = ((String) obj).length();  
  154.             }else if(obj instanceof Double){  
  155.                 length = ((String) obj).length();  
  156.             }else if(obj instanceof Float){  
  157.                 length = ((String) obj).length();  
  158.             }else{  
  159.                 throw new IllegalStateException("参数不正确");  
  160.             }  
  161.         }else{  
  162.             throw new IllegalStateException("参数不正确");  
  163.         }  
  164.         return length;  
  165.     }  
  166.   
  167. }  
  168. </pre>  
  169. <br>  
  170. <br><strong>生成</strong>结果:index.html  
  171. <br><pre name="code" class="java"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  172. <html>  
  173.   <head>  
  174.     <title>Index.html</title>  
  175.       
  176.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  177.     <meta http-equiv="description" content="this is my page">  
  178.     <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  179.   </head>  
  180.     
  181.   <body>  
  182.     你好!chenlei<br>  
  183.     栏目test  
  184.     10  
  185.     栏目  
  186.       
  187.    <div>  
  188.      
  189.    <span >  
  190. <br>感觉自定义函数功能不错,但是也麻烦了些,两个函数就要写两个类。  
  191. <br>如果能归类就好了,比如对字符串的操作,一个自定义函数中不同的方法就可以搞定。  
  192.   </pre>  
原创粉丝点击