How to call a Java method from a Velocity template

An Object can be set in the context of the Velocity Template. That Object can then be called from the template using it's name.

Example:

Lets assume that we want the template to call the hello method from the VelocityJavaMethodExample Object.

public class VelocityJavaMethodExample {

	public String hello( String input ){
		return "Hello " + input;
	}
}

1- Create the following java file:

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 VelocityJavaMethodRun {

	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( "example3.vm" );

        // Create the Context
        VelocityContext context = new VelocityContext();
        context.put("MyVariable", new VelocityJavaMethodExample() );

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

Create the following template called example3.vm:


This is a test

Call java method: $MyVariable.hello( $input )


The output will be:

This is a test

Call java method: Hello World

References:

Java 8
Velocity user-guide
Velocity Project

Share this article:

Recent Comments