Velocityの文字化け

JavaのVelocity(テンプレートエンジン)を使った際に文字化けに遭遇したので、
そのときの対策をば。

サンプルPGを出すほうが早いってことで、以下サンプル。

まず、テンプレートを扱うクラス


package test.template;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class CreateHtml {
private String template_path;
public CreateHtml(){
}
public CreateHtml(String path){
this.template_path = path;
}
public void create() throws Exception{
//プロパティー設定
Properties p = new Properties();
p.setProperty("input.encoding", "Shift_JIS");
Velocity.init(p);
VelocityContext vc = new VelocityContext();
vc.put("Velocity","Velocity Test!!");
StringWriter sw = new StringWriter();
//テンプレートの取得
Template template = Velocity.getTemplate(template_path);
// テンプレートとデータを統合
template.merge(vc,sw);
System.out.println(sw.toString());
sw.flush();
}
}


//プロパティー設定
Properties p = new Properties();
p.setProperty("input.encoding", "Shift_JIS");
Velocity.init(p);

この部分で文字コードを設定してます。
velocity.propertiesファイルを変更しても上手くいかなかったので、こっちで対応しました。
しかし文字コードってなんてうざいんざましょ。

下はそれを呼び出すクラス。
参考までに。


package test.template.test;
import test.template.CreateHtml;
public class TemplateTest {
public static String file_path = "/template/test.vm";
public static void main(String[] args) {
CreateHtml cmrh = new CreateHtml(file_path);
try{
cmrh.create();
} catch (Exception e) {
e.printStackTrace();
}
}
}

以上です。