標籤:.com city time private 產生 this oci classname led
這裡面是關於velocity的一些用法,比較基礎的使用。
velocity產生javaBean
一、定義一個簡單的bean類
public class ClassBean { private String name; private String comment; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; }}
二、產生javabean的velocity代碼
private VelocityEngine init() { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); return ve;}
@Testpublic void velocity_test_2() { VelocityEngine ve = init(); Template t = ve.getTemplate("template/ClassVelocity.vm"); VelocityContext ctx = new VelocityContext(); // 資料 List<ClassBean> classBeans = new ArrayList<>(); ClassBean classBean1 = new ClassBean(); classBean1.setName("username"); classBean1.setComment("使用者名稱"); ClassBean classBean2 = new ClassBean(); classBean2.setName("password"); classBean2.setComment("密碼"); ClassBean classBean3 = new ClassBean(); classBean3.setName("address"); classBean3.setComment("地址"); classBeans.add(classBean1); classBeans.add(classBean2); classBeans.add(classBean3); ctx.put("className", "Person"); ctx.put("list", classBeans); StringWriter sw = new StringWriter(); t.merge(ctx, sw); System.out.println(sw.toString());}
三、ClassVelocity.vm的內容如下
##首字母大寫#macro(initUpperCase $field)$field.toUpperCase().substring(0,1)$field.substring(1)###endpublic class $className {#foreach($bean in $list) private String $bean.getName(); // $bean.getComment()#end#foreach($bean in $list) #set($filed = $bean.getName()) public String get#initUpperCase($filed)() { return $filed; } public void set#initUpperCase($filed)(String $filed){ this.$filed = $filed; }#end}
四、產生的程式碼如下:
public class Person { private String username; // 使用者名稱 private String password; // 密碼 private String address; // 地址 public String getUsername() { return username; } public void setUsername(String username){ this.username = username; } public String getPassword() { return password; } public void setPassword(String password){ this.password = password; } public String getAddress() { return address; } public void setAddress(String address){ this.address = address; }}
友情連結
- 關於velocity的基礎使用,參見部落格http://www.cnblogs.com/huhx/p/baseusewebvelocity1.html
web基礎----->模板引擎Velocity的使用(二)