使⽤Velocity将java代码转换成JS代码
为什么要⽤Velocity:项⽬中需要将JAVA代码⽣成JS代码,但是⼜不想在JS中import JAVA类,⽽且类中有很多枚举元素,如果⼿动的将枚举元素转换成JS对象会很耗时,所以采⽤Velocity模板技术让JAVA枚举对象⾃动转换成JS⽂件。
准备⼯作:
Velocity相关架包:Velocity-1.5.jar等
熟悉Velocity相关语法
下⾯贴上我写得代码
要转换成JS的JAVA枚举类:
[java]
1. /**
2. * we copy the struct from taobao
3. * dev.open.taobao/dev/index.php/%E9%94
4. * %99%E8%AF%AF%E7%A0%81%E4%B8%80%E8%A7%88%E8%A1%A8
5. *
6. * @author stream
7. *
8. */
9. public enum PlatformError {
10. HTTP_CONNECTION_INVALID("2","Http Connection Invalid"),
11. UPLOAD_FAIL("3", "Upload Fail"),
12. APP_CALL_LIMITED("7", "App Call Limited"),
13. HTTP_ACTION_NOT_ALLOWED("9","Http Action Not Allowed"),
14. SERVICE_CURRENTLY_UNAVAILABLE("10", "Service Currently Unavailable"),
15. INSUFFICIENT_ISV_PERMISSIONS("11", "Insufficient ISV Permissions"),
16. INSUFFICIENT_USER_PERMISSIONS("12", "Insufficient User Permissions"),
17. INSUFFICIENT_PARTNER_PERMISSIONS("13", "Insufficient Partner Permissions"),
18. REMOTE_SERVICE_ERROR("15", "Remote service error"),
19. MISSING_METHOD("21", "Missing Method"),
20. INVALID_METHOD("22", "Invalid Method"),
21. INVALID_FORMAT("23", "Invalid Format"),
22. MISSING_SIGNATURE("24", "Missing Signature"),
23. INVALID_SIGNATURE("25", "Invalid Signature"),
24. MISSING_SESSION("26","Missing session"),
25. INVALID_SESSION("27", "Invalid Session"),
26. MISSING_APP_KEY("28", "Missing App Key"),
27. INVALID_APP_KEY("29", "Invalid App Key"),
28. MISSING_TIMESTAMP("30", "Missing Timestamp"),
29. INVALID_TIMESTAMP("31","Invalid Timestamp"),
30. MISSING_VERSION("32", "Missing Version"),
31. INVALID_VERSION("33", "Invalid Version"),
32. UNSUPPORTED_VERSION("34", "Unsupported Version"),
33. MISSING_REQUIRED_ARGUMENTS("40", "Missing required arguments"),
33. MISSING_REQUIRED_ARGUMENTS("40", "Missing required arguments"),
34. INVALID_ARGUMENTS("41", "Invalid arguments"),
35. FORBIDDEN_REQUEST("42", "Forbidden Request"),
36. PARAMETER_ERROR("43","Parameter Error"),
37. INVALID_ENCODING("47", "Invalid encoding"),
38. MISSING_TARGET("50", "Missing Target"),
39. MISSING_LICENSE("51", "Missing License"),
40. MISSING_APPPARAMS("52", "Missing AppParams"),
41. INVALID_LICENSE2TARGET("53", "Invalid License To Target"),
42. INVALID_NODE("54", "Invalid Node"),
43.
44. // above 100
45. OVERTIME_SESSIONKEY("100", "overtime session key "),
46. INVALID_SESSIONKEY("101","invalid session key"),
47. NOTMATCH_APP_KEY("108","app key is not match user"),
48.
49. //add by stream 第三⽅平台未知错误,产⽣的原因主要是匹配不到我们平台的错误code
50. ThirdPlatform_UNKNOW_ERROR("102","unknow error from third platform");
51.
52. private String code;
53.
54. private String msg;
55.
56. private PlatformError(String code, String msg) {
57. de = code;
58. this.msg = msg;
59. }
60.
61. public String code() {
62. return code;
63. }
64.
65. public String msg() {
66. return msg;
js arguments67. }
68.
69. public static PlatformError getErrorByCode(String code) {
70. for (PlatformError error : PlatformError.values())
71. if (de().equals(code))
72. return error;
73. return null;
74. }
75.
76. public static void main(String[] args) {
77. System.out.println(PlatformError.FORBIDDEN_REQUEST.msg());
78. }
79. }
编写Velocity转换类
[java]
1. import java.io.File;
2. import java.io.FileOutputStream;
3. import java.io.StringWriter;
4. import java.util.ArrayList;
5. import java.util.HashMap;
6. import java.util.List;
7. import java.util.Map;
8. import java.util.Properties;
9.
10. import org.apache.velocity.Template;
11. import org.apache.velocity.VelocityContext;
12. import org.apache.velocity.app.Velocity;
13. import org.apache.velocity.app.VelocityEngine;
14.
15. public class VelocityTest {
16.
17. public static void main(String[] args) throws Exception {
18. //创建引擎
19. VelocityEngine velocityEngine = new VelocityEngine();
20.
21. //设定输⼊输出编码可⽀持中⽂
22. Properties prop = new Properties();
23. prop.setProperty(Velocity.ENCODING_DEFAULT, "utf-8");
24. prop.setProperty(Velocity.INPUT_ENCODING, "utf-8");
25. prop.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
26.
27. //可以根据属性对象或者属性⽂件进⾏定义,原理是⼀样的.
28. velocityEngine.init(prop);
29.
30. //取得VTL定义的⽂件获取模板对象
31. Template template = Template("/src/cn/demo/util/velocity/template.vm");
32.
33. //新创⼀个Velocity上下⽂
34. VelocityContext velocityContext = new VelocityContext();
35.
36. //放⼊VTL中定义的变量值
37. velocityContext.put("name", "ChenST");
38. velocityContext.put("address", "淘宝商城");
39.
40. List<String> products = new ArrayList<String>();
41. products.add("百事可乐");
42. products.add("可⼝可乐");
43. //可放⼊⼀个ArrayList集合代表数组
44. velocityContext.put("products", products);
45.
46. Map<String, String> map = new HashMap<String, String>();
47. map.put("key", "mapValue");
48. //可放⼊⼀个Map结构的对象
49. velocityContext.put("map", map);
50.
51. //可放⼊⼀个⾃定义对象
52.
53. velocityContext.put("error", PlatformError.values());
54.
55. StringWriter stringWriter = new StringWriter();
56. //根据模板定义的内容进⾏合并,并将结果输出给流对象
57. (velocityContext, stringWriter);
58. System.out.String());
59. //⽣成JS⽂件
60. new FileOutputStream(new File("E:\\demo.js")).String()
61. .getBytes());
62.
63. }
64. }
定义模板⽂件 /src/cn/demo/util/velocity/template.vm
[plain]
1. //velocity测试
2. var test = {
3. name:${name},
4. address:${address},
5. products:
6. #foreach($p in $products)
7. #if($velocityCount==1)
8. ${p}
9. #end
10. #if($velocityCount!=1)
11. ,${p}
12. #end
13. #end,
14. map:{
15. #foreach($m in $Set())
16. #if($velocityCount==1)
17. ${m.key}:${m.value}
18. #end
19. #if($velocityCount!=1)
20. ,${m.key}:${m.value}
21. #end
22.
23. #end
24. }
25. }
26.
27. //错误定义
28. var platformError = {
29. #foreach( $e in $error )
30. #if($velocityCount==1)
31. ${e}:{code:"${e.code()}",msg:"${e.msg()}"}#end #if($velocityCount!=1),${e}:{code:"${e.code()}",msg:"${e.msg()}"}
32. #end
33. #end
34. }
运⾏main⽅法⽣成的demo.js为
[javascript]
1. //velocity测试
2. var test = {
3. name:ChenST,
4. address:淘宝商城,
5. products:百事可乐,可⼝可乐,
6. map:{
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论