I need to use Velocity from Java-code in a web-application (I use it as mail-templates processor).
So, I have a standard code:
VelocityEngine ve = new VelocityEngine ();
try {
ve.init ();
Template t = ve.getTemplate (templatePath);
...
} catch (Exception e) {
throw new MailingException (e);
}
This code always throws the ResourceNotFoundException
. Where should I place my templates in web-application (WEB-INF? classpath? etc?) and how should I specify path (i.e. what should I pass as templatePath
)?
SETTING UP VELOCITY TEMPLATES
I ended up using this question to solve my problem of setting up the template path. I am using velocity for templating html emails.
Here is a good couple of methods you can use that illustrate how the template path is set up. It sets the property 'file.resource.loader.path' to the absolute path. I created a directory for templates, and then right clicked on the template file to get the full path (In Eclipse). You use that full path as the value of the file.resource.loader.path property. I also added the 'runtime.log.logsystem.class' property, and set it because I was getting exceptions complaining about logging.
UTILTY VELOCITY METHODS
HOW TO USE ABOVE CODE, CREATING A VELOCITY CONTEXT TO FEED TO UTILTY METHOD
Here is how you can use the above methods. You simply specify the filename of the template file, and create a simple
VelocityContext
context to store your template variables.EXAMPLE TEMPLATE HTML
The variables can be accessed like (in my case saved in file
email_template_2015_10_09.vm
):You need to initialize Velocity first by calling
Velocity.init()
(in the singleton model of usage), orVelocityEngine.init()
(if you use a separate instance), and passing appropriate configuration parameters. These include the resource loader configuration.Where to put your template files depends in which resource loader you choose - there are file, classpath, jar, url etc. resource loaders available.
If you use the file resource loader, the template path should be an absolute (directory/file) path. With the jar resource loader, though, it must not be an absolute path (if your templates are within a jar, that is). This is also true for links within your templates, i.e. if one of your templates includes another one by absolute path, the jar resource loader will fail to load it.