1. Add the velocity JAR files to your project classpath as shown below.
2. Create a velocity.properties file as follows. In this example the templates files will be read from the file system , you can read them from the classpath if you wish. You will see that from this example below the velocity template files are in the SRC directory of the project so I can edit them from the IDE itself.
resource.loader = file
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = C:/jdev/jdevprod/11113/jdeveloper/jdev/mywork/VelocityDemo/Demo/src/templates
file.resource.loader.cache = true
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = C:/jdev/jdevprod/11113/jdeveloper/jdev/mywork/VelocityDemo/Demo/src/templates
file.resource.loader.cache = true
3. In the directory "C:/jdev/jdevprod/11113/jdeveloper/jdev/mywork/VelocityDemo/Demo/src/templates" create a helloworld.vm template file as follows
Hello $name! Welcome to Velocity!
4. Now create a java class as follows
package support.au.demos.velocity; import java.io.StringWriter; import java.net.URL; import java.util.Properties; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; public class HelloWorld { public HelloWorld() { } public static void main(String[] args) throws Exception { /* first, get and initialize an engine */ VelocityEngine ve = new VelocityEngine(); Properties props = new Properties(); URL url = ClassLoader.getSystemResource("velocity.properties"); props.load(url.openStream()); ve.init(props); /* next, get the Template */ Template t = ve.getTemplate( "helloworld.vm" ); /* create a context and add data */ VelocityContext context = new VelocityContext(); context.put("name", "World"); /* now render the template into a StringWriter */ StringWriter writer = new StringWriter(); t.merge( context, writer ); /* show the World */ System.out.println( writer.toString() ); } }
5. Your project would look something like this
6. Run HelloWorld to verify the output as shown below.
Hello World! Welcome to Velocity!
1 comment:
Thanks alot for this usefull tutorial! This is the one that works for me.
Post a Comment