2011年4月12日火曜日

Velocity

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

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

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

参考

テンプレート:index.vm

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



データクラス:user.java
public class user {
private int id = 0;
private String name = "";
private int weight = 0;
private int height = 0;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public user(int id, String name, int weight, int height) {
this.id = id;
this.name = name;
this.weight = weight;
this.height = height;
}
public user() {}

}



マージクラス:test.java
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class test {
public static void main(String[] args) {
user user = new user(1000, "銅鑼 衛門", 100, 200);
Velocity.init();
VelocityContext context = new VelocityContext();
context.put("user", user);

StringWriter stringWriter = new StringWriter();
Template template = Velocity.getTemplate("index.vm", "UTF-8");
template.merge(context, stringWriter);
System.out.println(stringWriter.toString());
stringWriter.flush();
}
}
 

0 件のコメント:

コメントを投稿