How to render text using velocity in Java

This example shows how to Generate a page using Velocity in Java.

Create the following template called example.vm:


Hello $name!
	

The code sets the variables in the context. The context is passed to the template. Then the rendering is processed using the context.

Create the following java file:

import static org.junit.Assert.assertEquals;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

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

public class VelocitySimple {

	public static void main(String[] argv){

		// Source directory
		String sourceDirectory = "V:/tmp/velocity/";
		
		
		// Create the velocity engine
        VelocityEngine ve = new VelocityEngine();
        
        ve.setProperty( "resource.loader", "file");
        ve.setProperty( "file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
        ve.setProperty( "file.resource.loader.path", sourceDirectory);
        ve.setProperty( "file.resource.loader.cache", true);
        ve.setProperty( "file.resource.loader.modificationCheckInterval", "2");

        ve.init();		
		
        // Get the template
        Template t = ve.getTemplate( "example.vm" );

        // Create the 
        VelocityContext context = new VelocityContext();
        context.put("name", "World");

        try {
	        // Create the output file
	        Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( new File( sourceDirectory + "example.txt" ) ), "UTF8") );
	    	
	        t.merge( context, out);
	        
	        out.close();
        } catch ( Exception e ){
        	e.printStackTrace();
        }
	}
	
}

The generated file example.txt will be:

	
Hello World!
	

The code first initilize the VelocityEngine using the file resource loader. It set the loader path to the directory contening the templates. Then it gets a template from the template directory using the getTemplate method. A set of variables is set in the VelocityContext, here it's name = World, that context is then passed to the merger method that generate the output files. The variables defined as $name as replaced in the template.


References:

Velocity

Recent Comments