`
shuai1234
  • 浏览: 930684 次
  • 性别: Icon_minigender_1
  • 来自: 山西
社区版块
存档分类
最新评论

Velocity与Struts-- 静态页生成

    博客分类:
  • java
 
阅读更多

-
-
在Struts中有两种使用Velocity的方法,一种是利用Velocity的vm模板进行页面展示,一种则是利用Velocity来生成静态页面。以下介绍在Struts 1.*版本中使用Velocity模板生成静态页面的过程。

    思路是访问一个Action,在Action中进行静态页面的生成,最终该Action跳转到生成好的静态页面中。

步骤为:
1. 获取VelocityContext,该对象中包含了需要展示的数据
2. 获取指定路径下的vm模板内容
3. 根据Velocity模板,生成字符串
4. 根据指定路径及文件名创建文件
5. 将转换好的模板文件写入指定文件中

源码如下:
Velocity模板

<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 <title>StrutsSample_1</title>
</head>
<body>
 <h3>StrutsSample</h3>
 <table width="400" border="1">
  #foreach($name in $list)
      <tr> <td>$name</td> </tr>
  #end
 </table>
</body>
</html>

 

public class CreateHtmlPage extends DispatchAction {
 public ActionForward createStaticPage(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  ActionForward forward = new ActionForward();
  ActionMessages errors = new ActionMessages();
  String webServer_dir = "D:/Tomcat6/webapps/Mixele_Velocity";
  
  String filepath = webServer_dir + "/success.htm"; //需要生成的静态页
  String vmpath = webServer_dir + "/templates/namelist.vm"; //Velocity模板
  
  VelocityContext context = getContext();
  String templatebody = getTemplateBody(vmpath);
  String str = createHtmlStrByVelocity(context, templatebody);
  File htmlfile = createFile(filepath);
  writerTxtFile(htmlfile, str);
  
  if (!errors.isEmpty()) {
   saveErrors(request, errors);
   forward = new ActionForward(mapping.getInput());
  } else {
   forward = new ActionForward("/success.htm");
  }
  return forward;
 }
 
 /** 获取VelocityContext对象,并向其中注入模板需要展现的数据 */
 public VelocityContext getContext() {
  /* 这里需要注意,因为在web.xml中配置了VelocityViewServlet
   * 所以这里Velocity会在系统启动时初始化
   * 如果没有配置,需要先在这里进行Velocity的初始化工作 */
  VelocityContext context = new VelocityContext();
  List<String> list = new ArrayList<String>();
  String name = null;
  for(int i=0;i<20;i++){
   name = "Hoffman YoYo "+i+" Name";
   list.add(name);
  }
  context.put("list", list);
  return context;
 }
 
 /** 通过指定路径获取vm模板并提取模板内容 */
 public String getTemplateBody(String vmpath) {
  File file = new File(vmpath);
  BufferedReader reader = null;
  StringBuffer strbf = new StringBuffer("");
  try {
   reader = new BufferedReader(new FileReader(file));
   String tempString = null;
   int line = 1;
   while ((tempString = reader.readLine()) != null) {
    strbf.append(tempString);
    line++;
   }
   reader.close();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (reader != null) {
    try {
     reader.close();
    } catch (IOException e1) {
     e1.printStackTrace();
    }
   }
  }
  return strbf.toString();
 }
 
 /** 根据Velocity模板,生成字符串 */
 public String createHtmlStrByVelocity(VelocityContext context, String vmbody) {
  StringWriter writer = new StringWriter();
  try {
   Velocity.evaluate(context, writer, "myString", vmbody);
  } catch (ParseErrorException e) {
   e.printStackTrace();
  } catch (MethodInvocationException e) {
   e.printStackTrace();
  } catch (ResourceNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return writer.toString();
 }
 
 /** 在指定路径中创建由Velocity解析出的html文件
  * 当文件存在时,删除该文件,重新创建 */
 public File createFile(String filepath) {
        File file = new File(filepath);
        if(file.exists() && file.isFile()) {
         boolean delFileSuccess = file.delete(); //文件存在删除之
            if(!delFileSuccess) {
             System.out.println("删除文件" + filepath + "失败!");
            }
            try {
             boolean cresteFileSuccess = file.createNewFile();
                if (!cresteFileSuccess) {
                 System.out.println("创建文件" + filepath + "失败!");
                }
   } catch (IOException e) {
    e.printStackTrace();
   }
        }
  return file;
 }
 
 /** 写文本文件 */
 public void writerTxtFile(File filepath, String str) {
  PrintWriter out = null;
  try {
   out = new PrintWriter(new BufferedWriter(new FileWriter(filepath), 1024));
  } catch (IOException e) {
   e.printStackTrace();
  }
  out.println(str);
  out.flush();
  out.close();
 }
}

通过以上的代码,即可将赋予VelocityContext中的数据与VM模板组合,生成静态页面。
以上代码很多地方都是硬编码,其实在实际工程中,静态化的步骤不会发生太大变化,只是模板与生成页面的路径会有更复杂的获取过程。
文章出处:飞诺网(www.diybl.com):http://www.diybl.com/course/3_program/java/javajs/20100719/456479.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics