2011年4月12日火曜日

Velocity

HTMLのテンプレートに変数を代入してから表示させる事が出来る。
他にもテキストファイルなら埋め込み可能。

これによって構成とデータを別々に管理しやすくなると。

eclipse用は→ここ
velocity-1.7.zip
この中のvelocity-1.7-dep.jarを使用。

参考

テンプレート:index.vm

  1. 識別番号:$user.id  
  2. 名前:$user.name  
  3. 体重:$user.weight  
  4. 身長:$user.height  



データクラス:user.java
  1. public class user {  
  2.     private int id = 0;  
  3.     private String name = "";  
  4.     private int weight = 0;  
  5.     private int height = 0;  
  6.     public int getId() {  
  7.         return id;  
  8.     }  
  9.     public void setId(int id) {  
  10.         this.id = id;  
  11.     }  
  12.     public String getName() {  
  13.         return name;  
  14.     }  
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.     public int getWeight() {  
  19.         return weight;  
  20.     }  
  21.     public void setWeight(int weight) {  
  22.         this.weight = weight;  
  23.     }  
  24.     public int getHeight() {  
  25.         return height;  
  26.     }  
  27.     public void setHeight(int height) {  
  28.         this.height = height;  
  29.     }  
  30.     public user(int id, String name, int weight, int height) {  
  31.         this.id = id;  
  32.         this.name = name;  
  33.         this.weight = weight;  
  34.         this.height = height;  
  35.     }  
  36.     public user() {}  
  37.   
  38. }  



マージクラス:test.java
  1. import java.io.StringWriter;  
  2.   
  3. import org.apache.velocity.Template;  
  4. import org.apache.velocity.VelocityContext;  
  5. import org.apache.velocity.app.Velocity;  
  6.   
  7. public class test {  
  8.     public static void main(String[] args) {  
  9.         user user = new user(1000"銅鑼 衛門"100200);  
  10.         Velocity.init();  
  11.         VelocityContext context = new VelocityContext();  
  12.         context.put("user", user);  
  13.           
  14.         StringWriter stringWriter = new StringWriter();  
  15.         Template template = Velocity.getTemplate("index.vm""UTF-8");  
  16.         template.merge(context, stringWriter);  
  17.         System.out.println(stringWriter.toString());  
  18.         stringWriter.flush();  
  19.     }  
  20. }  
 

0 件のコメント:

コメントを投稿