为什么要用Velocity:项目中需要将JAVA代码生成JS代码,但是又不想在JS中import JAVA类,而且类中有很多枚举元素,如果手动的将枚举元素转换成JS对象会很耗时,所以采用Velocity模板技术让JAVA枚举对象自动转换成JS文件。
准备工作:
Velocity相关架包:Velocity-1.5.jar等
熟悉Velocity相关语法
下面贴上我写得代码
要转换成JS的JAVA枚举类:
/**
* we copy the struct from taobao
* http://dev.open.taobao.com/dev/index.php/%E9%94
* %99%E8%AF%AF%E7%A0%81%E4%B8%80%E8%A7%88%E8%A1%A8
*
* @author stream
*
*/
public enum PlatformError {
HTTP_CONNECTION_INVALID("2","Http Connection Invalid"),
UPLOAD_FAIL("3", "Upload Fail"),
APP_CALL_LIMITED("7", "App Call Limited"),
HTTP_ACTION_NOT_ALLOWED("9","Http Action Not Allowed"),
SERVICE_CURRENTLY_UNAVAILABLE("10", "Service Currently Unavailable"),
INSUFFICIENT_ISV_PERMISSIONS("11", "Insufficient ISV Permissions"),
INSUFFICIENT_USER_PERMISSIONS("12", "Insufficient User Permissions"),
INSUFFICIENT_PARTNER_PERMISSIONS("13", "Insufficient Partner Permissions"),
REMOTE_SERVICE_ERROR("15", "Remote service error"),
MISSING_METHOD("21", "Missing Method"),
INVALID_METHOD("22", "Invalid Method"),
INVALID_FORMAT("23", "Invalid Format"),
MISSING_SIGNATURE("24", "Missing Signature"),
INVALID_SIGNATURE("25", "Invalid Signature"),
MISSING_SESSION("26","Missing session"),
INVALID_SESSION("27", "Invalid Session"),
MISSING_APP_KEY("28", "Missing App Key"),
INVALID_APP_KEY("29", "Invalid App Key"),
MISSING_TIMESTAMP("30", "Missing Timestamp"),
INVALID_TIMESTAMP("31","Invalid Timestamp"),
MISSING_VERSION("32", "Missing Version"),
INVALID_VERSION("33", "Invalid Version"),
UNSUPPORTED_VERSION("34", "Unsupported Version"),
MISSING_REQUIRED_ARGUMENTS("40", "Missing required arguments"),
INVALID_ARGUMENTS("41", "Invalid arguments"),
FORBIDDEN_REQUEST("42", "Forbidden Request"),
PARAMETER_ERROR("43","Parameter Error"),
INVALID_ENCODING("47", "Invalid encoding"),
MISSING_TARGET("50", "Missing Target"),
MISSING_LICENSE("51", "Missing License"),
MISSING_APPPARAMS("52", "Missing AppParams"),
INVALID_LICENSE2TARGET("53", "Invalid License To Target"),
INVALID_NODE("54", "Invalid Node"),
// above 100
OVERTIME_SESSIONKEY("100", "overtime session key "),
INVALID_SESSIONKEY("101","invalid session key"),
NOTMATCH_APP_KEY("108","app key is not match user"),
//add by stream 第三方平台未知错误,产生的原因主要是匹配不到我们平台的错误code
ThirdPlatform_UNKNOW_ERROR("102","unknow error from third platform");
private String code;
private String msg;
private PlatformError(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String code() {
return code;
}
public String msg() {
return msg;
}
public static PlatformError getErrorByCode(String code) {
for (PlatformError error : PlatformError.values())
if (error.code().equals(code))
return error;
return null;
}
public static void main(String[] args) {
System.out.println(PlatformError.FORBIDDEN_REQUEST.msg());
}
}
编写Velocity转换类
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
public class VelocityTest {
public static void main(String[] args) throws Exception {
//创建引擎
VelocityEngine velocityEngine = new VelocityEngine();
//设定输入输出编码可支持中文
Properties prop = new Properties();
prop.setProperty(Velocity.ENCODING_DEFAULT, "utf-8");
prop.setProperty(Velocity.INPUT_ENCODING, "utf-8");
prop.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
//可以根据属性对象或者属性文件进行定义,原理是一样的.
velocityEngine.init(prop);
//取得VTL定义的文件获取模板对象
Template template = velocityEngine.getTemplate("/src/cn/demo/util/velocity/template.vm");
//新创一个Velocity上下文
VelocityContext velocityContext = new VelocityContext();
//放入VTL中定义的变量值
velocityContext.put("name", "ChenST");
velocityContext.put("address", "淘宝商城");
List<String> products = new ArrayList<String>();
products.add("百事可乐");
products.add("可口可乐");
//可放入一个ArrayList集合代表数组
velocityContext.put("products", products);
Map<String, String> map = new HashMap<String, String>();
map.put("key", "mapValue");
//可放入一个Map结构的对象
velocityContext.put("map", map);
//可放入一个自定义对象
velocityContext.put("error", PlatformError.values());
StringWriter stringWriter = new StringWriter();
//根据模板定义的内容进行合并,并将结果输出给流对象
template.merge(velocityContext, stringWriter);
System.out.println(stringWriter.toString());
//生成JS文件
new FileOutputStream(new File("E:\\demo.js")).write(stringWriter.toString()
.getBytes());
}
}
定义模板文件 /src/cn/demo/util/velocity/template.vm
//velocity测试
var test = {
name:${name},
address:${address},
products:
#foreach($p in $products)
#if($velocityCount==1)
${p}
#end
#if($velocityCount!=1)
,${p}
#end
#end,
map:{
#foreach($m in $map.entrySet())
#if($velocityCount==1)
${m.key}:${m.value}
#end
#if($velocityCount!=1)
,${m.key}:${m.value}
#end
#end
}
}
//错误定义
var platformError = {
#foreach( $e in $error )
#if($velocityCount==1)
${e}:{code:"${e.code()}",msg:"${e.msg()}"}#end #if($velocityCount!=1),${e}:{code:"${e.code()}",msg:"${e.msg()}"}
#end
#end
}
运行main方法生成的demo.js为
//velocity测试
var test = {
name:ChenST,
address:淘宝商城,
products:百事可乐,可口可乐,
map:{
key2:mapValue2
,key1:mapValue1
}
}
//错误定义
var platformError = {
HTTP_CONNECTION_INVALID:{code:"2",msg:"Http Connection Invalid"}
,UPLOAD_FAIL:{code:"3",msg:"Upload Fail"}
,APP_CALL_LIMITED:{code:"7",msg:"App Call Limited"}
,HTTP_ACTION_NOT_ALLOWED:{code:"9",msg:"Http Action Not Allowed"}
,SERVICE_CURRENTLY_UNAVAILABLE:{code:"10",msg:"Service Currently Unavailable"}
,INSUFFICIENT_ISV_PERMISSIONS:{code:"11",msg:"Insufficient ISV Permissions"}
,INSUFFICIENT_USER_PERMISSIONS:{code:"12",msg:"Insufficient User Permissions"}
,INSUFFICIENT_PARTNER_PERMISSIONS:{code:"13",msg:"Insufficient Partner Permissions"}
,REMOTE_SERVICE_ERROR:{code:"15",msg:"Remote service error"}
,MISSING_METHOD:{code:"21",msg:"Missing Method"}
,INVALID_METHOD:{code:"22",msg:"Invalid Method"}
,INVALID_FORMAT:{code:"23",msg:"Invalid Format"}
,MISSING_SIGNATURE:{code:"24",msg:"Missing Signature"}
,INVALID_SIGNATURE:{code:"25",msg:"Invalid Signature"}
,MISSING_SESSION:{code:"26",msg:"Missing session"}
,INVALID_SESSION:{code:"27",msg:"Invalid Session"}
,MISSING_APP_KEY:{code:"28",msg:"Missing App Key"}
,INVALID_APP_KEY:{code:"29",msg:"Invalid App Key"}
,MISSING_TIMESTAMP:{code:"30",msg:"Missing Timestamp"}
,INVALID_TIMESTAMP:{code:"31",msg:"Invalid Timestamp"}
,MISSING_VERSION:{code:"32",msg:"Missing Version"}
,INVALID_VERSION:{code:"33",msg:"Invalid Version"}
,UNSUPPORTED_VERSION:{code:"34",msg:"Unsupported Version"}
,MISSING_REQUIRED_ARGUMENTS:{code:"40",msg:"Missing required arguments"}
,INVALID_ARGUMENTS:{code:"41",msg:"Invalid arguments"}
,FORBIDDEN_REQUEST:{code:"42",msg:"Forbidden Request"}
,PARAMETER_ERROR:{code:"43",msg:"Parameter Error"}
,INVALID_ENCODING:{code:"47",msg:"Invalid encoding"}
,MISSING_TARGET:{code:"50",msg:"Missing Target"}
,MISSING_LICENSE:{code:"51",msg:"Missing License"}
,MISSING_APPPARAMS:{code:"52",msg:"Missing AppParams"}
,INVALID_LICENSE2TARGET:{code:"53",msg:"Invalid License To Target"}
,INVALID_NODE:{code:"54",msg:"Invalid Node"}
,OVERTIME_SESSIONKEY:{code:"100",msg:"overtime session key "}
,INVALID_SESSIONKEY:{code:"101",msg:"invalid session key"}
,NOTMATCH_APP_KEY:{code:"108",msg:"app key is not match user"}
,ThirdPlatform_UNKNOW_ERROR:{code:"102",msg:"unknow error from third platform"}
}