velocity 模板引擎

来源:互联网 发布:中国软件测试中心 编辑:程序博客网 时间:2024/04/30 02:55

依赖的jar包:velocity-1.6.2.jar , velocity-tools-generic-2.0.jar , commons-collections-3.1.jar , commons-lang-2.4.jar

新建好模版文件 Template.java (文件格式没有限定,我这里测试使用这种格式生成一个javaBean) 。放在WEBROOT/template目录下.文件代码如下:

package ${package} /* 这里替换的字符穿是包名 **/public class ${className} {/* 这里需要替换的是 类名称*//** 循环该类的所有属性,columnDatas 是个List<Entity>,Entity是一个类,这个类有两个属性,一个是 type,标识该字段的类型,colName是该字段的名称 这里循环输出这个List<Entity> */#foreach( $item in $!{columnDatas} )private $item.type $item.colName ;   #set( $end=$item.colName.length() )  /* 计算属性的长度*/   #set( $str=$item.colName.substring( 1 ,$end ) )     #set( $start = $item.colName.substring(0,1).toUpperCase() ) /* 首字母大写 */   public void set$start$str($item.type $item.colName){   this.$item.colName = $item.colName ;      }   #set( $get = "get")    #if($item.type == "boolean" ) /* 如果是字段类型是boolean类型,get方法就是is开头*/   #set( $get = "is")  #end       public $item.type $get$start$str(){   return this.$item.colName;    }#end}

 现在模版类写好了,需要去替换这个模版类,将此类生成到一个文件夹中。

 

public class Demo {/* 获取工程的目录,WEBRoot*/public static String getRootPath() {String rootPath = "";try {File file = new File(Demo.class.getResource("/").getFile());rootPath = file.getParentFile().getParent();rootPath = java.net.URLDecoder.decode(rootPath, "utf-8");return rootPath;} catch (Exception e) {e.printStackTrace();}return rootPath;}/** 在static块中 初始化 VelocityEngine 类,这里面的参数我还不是很清楚,请阅读者 在评论中告知,*/static VelocityEngine ve;static {try {// 获取文件模板根路径String templateBasePath = getRootPath() + "\\template";Properties properties = new Properties();properties.setProperty(Velocity.RESOURCE_LOADER, "file");properties.setProperty("file.resource.loader.description" , "Velocity File Resource Loader");properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,templateBasePath);properties.setProperty(Velocity.FILE_RESOURCE_LOADER_CACHE, "true");properties.setProperty("file.resource.loader.modificationCheckInterval", "30"); properties.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS , "org.apache.velocity.runtime.log.Log4JLogChute");properties.setProperty("runtime.log.logsystem.log4j.logger" , "org.apache.velocity");properties.setProperty("directive.set.null.allowed", "true");VelocityEngine velocityEngine = new VelocityEngine();velocityEngine.init(properties);ve = velocityEngine;} catch (Exception e) { e.printStackTrace();}}static String CONTENT_ENCODING = "UTF-8" ;public static void main(String[] args) throws Exception {Template template = ve.getTemplate( "Template.java", CONTENT_ENCODING );  File file = new File( "C:\\" + "a.java" );  /* 定义输出替换文件的目录 */FileOutputStream fos = new FileOutputStream(file);  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,CONTENT_ENCODING) );  VelocityContext context = new VelocityContext() ;  /* 定义输出类中需要替换的对象 */context.put( "className" ,  "Person" ) ; /* 替换类名*/context.put( "package" ,  "com.entity" ) ; /* 替换报名 */List<Entity> entities = new ArrayList<Entity>() ;entities.add( new Entity( "String" , "name" ) ) ;  entities.add( new Entity( "String" , "address" ) ) ;  entities.add( new Entity( "boolean" , "flag" ) ) ; context.put("columnDatas", entities ) ;  /* 替换属性名称,和setter,getter */template.merge(context, writer);  /* 执行替换方法*/writer.flush();    writer.close();     fos.close(); }}

 

以上代码生成的文件就是这样:

package com.entitypublic class Person {private String name ;   public void setName(String name){   this.name = name ;      }             public String getName(){   return this.name;    }private String address ;   public void setAddress(String address){   this.address = address ;      }             public String getAddress(){   return this.address;    }private boolean flag ;   public void setFlag(boolean flag){   this.flag = flag ;      }             public boolean isFlag(){   return this.flag;    }}