爲什麼要用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
- }
- //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"}
- }