groovy : velocity 模板

从 http://mirror.bit.edu.cn/apache//velocity/engine/1.7/ 下载 velocity-1.7.zip

解压后将 velocity-1.7-dep.jar copy to GROOVY_HOME/lib/

Vm_test.groovy

import groovy.sql.Sql;
import java.io.*;
import java.util.Properties; 

import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
 
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

class Vm_test {

    static void main(args){
        def fundcode ='';
        if (args.size() ==1){
            fundcode = args[0];
        } else {
            println " usage: groovy vm_test fundcode ";
            return;
        }
        assert fundcode.size() ==6
        String path = "/jsp/"; 
        String templateFile = "vm/result.vm";
  			String fileName = path + templateFile;
  			System.out.println(fileName);
  
			  File file = new File(fileName);
			  if (!file.exists())
			  {
			  		println("文件不存在");
			  		return;
			  }
        String Driver;
        String URL;
        String user;
        String pass;
        try {
            Properties props = new Properties();
            File infile = new File("./","mysql.properties");
            FileInputStream ins = new FileInputStream(infile);
            props.load(ins);
            ins.close();

            Driver = props.getProperty("driver");
            URL = props.getProperty("url");
            user = props.getProperty("username");
            pass = props.getProperty("password");

        } catch (IOException ex) {
                ex.printStackTrace();
        }
        Sql db = Sql.newInstance(URL, user, pass, Driver);
        def stmt ="select rq,jz,ljjz from jjjz where dm= ? order by rq";
        int j =0;
        // data model
        // Map<String,Object> root = new HashMap<String,Object>();
        ArrayList<Map<String, Object>> alist = new ArrayList<Map<String, Object>>();
        
        db.eachRow(stmt,[fundcode]){ r ->
						alist.add(['rq':r[0],'jz':r[1],'lljz':r[2]]);
						j++;
        }
        db.close();
        
    // 创建引擎  
    	VelocityEngine ve = new VelocityEngine();
    //ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
    //ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
          
    // 设置模板加载路径,这里设置的是vm下  
    	Velocity.setProperty(Velocity.RESOURCE_LOADER, path);  
			Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);  
			Template tp = null;
    	try {  
      	// 进行初始化操作  
      	ve.init("velocity.properites");  
      // 加载模板,设定模板编码   
      	tp = ve.getTemplate(templateFile, "gbk");  
      // 也可以使用
      // loadpath是路径地址   
      // 设置初始化数据  
        VelocityContext context = new VelocityContext();  
        context.put("title", "查询基金净值");  
        context.put("fundcode", fundcode);  
			  context.put("rows", alist); 
 
        // outfile
        def fn = "${fundcode}.html"
        def outfile = new File(fn);
        def fos = new FileOutputStream(outfile);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos,"GBK"));
        // 处理合并
        if (tp != null) tp.merge(context, out); 
        out.flush();
        out.close();
        println " output ${j} rows";
        println " outfile: ${fn}";       
			}
        catch( ResourceNotFoundException rnfe )
        {
            System.out.println("Example : error : cannot find template " + templateFile );
        }
        catch( ParseErrorException pee )
        {
            System.out.println("Example : Syntax error in template " + templateFile + ":" + pee );
        } 
        catch (Exception e) {  
          e.printStackTrace();  
        }  
    }
}

vm/result.vm

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GBK" />
  <title>查询基金净值  </title>
<style>
   table {border-collapse:collapse;}
   th,td {border: black solid 1px; font-size:12px; padding-left:5px; white-space:nowrap;}
</style>
</head>
<body>
<h3>$fundcode </h3>
<table>
 <thead>
  <tr>
  <th>日期 </th>
  <th>基金净值 </th>
  <th>累计净值 </th>
  </tr>
 </thead>
 <tbody>
  #foreach( $row in $rows)
  <tr>
    <td>$row.rq</td>
	<td>$row.jz</td>
	<td>$row.lljz</td>
  </tr>
  #end
 </tbody>
</table>
</body>
</html>
通过查看源码终于发现velocity的vm文件是以项目工程名为根的,也就是说把文件要放在项目工程的目录下,

才能直接使用getTemplate("example.vm").如果要放在子目录下,比如放在项目的子目录vm/下,

则必须使用如下代码才行:  getTemplate("vm/example.vm");

猜你喜欢

转载自blog.csdn.net/belldeep/article/details/80821939