Java用テンプレートエンジンVelocity

Java用テンプレートエンジンvelocityを使用してみました.

PHPで言うところのSmartyみたいなものです.

サンプルコード

以下のファイルはすべて同じパッケージの中にあるものとします.

package sample;

import java.io.StringWriter;
import java.util.Properties;

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


/**
 *  Template Engine.
 *
 * @author Takahiro HATORI
 */
public class TemplateEngine {

    VelocityContext _context;
    Template _template;

    public TemplateEngine(String templatePath) throws Exception {
        Properties p = new Properties();
        p.setProperty("input.encoding", "UTF-8");
        p.setProperty("resource.loader", "class");
        p
                .setProperty("class.resource.loader.class",
                        "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

        try {
            Velocity.init(p);
        } catch (Exception e) {
            throw new Exception(e);
        }

        Template template = null;
        try {
            template = Velocity.getTemplate(templatePath, "UTF-8");
        } catch (Exception e) {
            throw new Exception(e);
        }
        _template = template;

        VelocityContext context = new VelocityContext();
        _context = context;

    }

    public void assign(String key, Object value) {
        _context.put(key, value);
    }

    public String getString() throws Exception {

        StringWriter writer = new StringWriter();

        try {
            _template.merge(_context, writer);
        } catch (Exception e) {
            throw new Exception(e);
        }
        String str = writer.toString();

        return str;
    }

}
package sample;

/**
 *  Template Engine Sample.
 *
 * @author Takahiro HATORI
 */
public class Sample {

    public void main() throws Exception {
        TemplateEngine engine = new TemplateEngine(
                "sample/temlate.vm");

        engine.assign("message", "Hello, World!");

        System.out.println(engine.getString());
    }
}
<html>
  <head>
    <title>Sample</title>
  </head>
  <body>
    <p>$message</p>
  </body>
</html>