Monday, June 7, 2010

Velocity Template in Web Application

I don't use Velocity a lot.  Initially, I was just using it for mail templates in a standalone application.  The setup is simple:
VelocityEngine velocity = new VelocityEngine();
velocity.setProperty(Velocity.RESOURCE_LOADER, "class");
velocity.setProperty("class.resource.loader.class",
        ClasspathResourceLoader.class.getName());
velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS,
        Log4JLogChute.class.getName());
velocity.setProperty("runtime.log.logsystem.log4j.logger", "mail");
Here I use ClasspathResourceLoader along with Log4j as logging method.

Then I decide to use Velocity again in a web application. To use Velocity in web application, however, you'll need a WebappResourceLoader.  WebappResourceLoader is available in VelocityTools.  However, you can always write your own.

Since I only needed this one class, I copied over the class from VelocityTools and made following configuration in my servlet:
VelocityEngine velocity = new VelocityEngine();
velocity.setProperty(Velocity.RESOURCE_LOADER, "webapp");
velocity.setProperty("webapp.resource.loader.class",
        WebappResourceLoader.class.getName());
velocity.setProperty("webapp.resource.loader.path", "/templates/");
velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS,
        ServletLogChute.class.getName());
I did try using Log4JLogChute, but somehow couldn't get it to log messages.

No comments: