9.9. Invoking Methods in a Template

Problem

You need to invoke methods from a Velocity template.

Solution

Use Velocity to access public methods on an object in the VelocityContext. Bind an object to the VelocityContext and reference methods on these objects in a Velocity template. The following template, available on the classpath at scripting/velocity/results.vm, invokes the average( ), min( ), and max( ) methods on a StatUtil object bound to the reference $stat:

** Aggregate Statistics

Average: $stat.average( $results.scores )%
Lowest: $stat.min( $results.scores )%
Highest: $stat.max( $results.scores )%

** Scores:
#foreach( $student in $results.students )
    #score( $student 50 )
#end

More results are available here:
http://www.test.com/detail?test={results.id}

The StatUtil object, which is bound to $stat, computes basic statistics on integer arrays. This class definition is:

public class StatUtil {
    public int average(int[] array) {
        int sum = 0.0;
        for( int i = 0; i < array.length; i++ ) {
            sum += array[i];
        }
        return( sum / array.length );
    }

    public int min(int[] array) {
        int min = Integer.MAX_VALUE;
        for( int i = 0; i < array.length; i++) {
            if( array[i] < min) { min = array[i]; }
        }
        return( min );
    }

    public int max(int[] array) {
        int max = Integer.MIN_VALUE;
        for( int i = 0; i < array.length; i++) {
            if( array[i] > max) { max = array[i]; }
        }
        return( max );
    }
}

The template shown above is loaded from the classpath, and a StatUtil object is added to the VelocityContext . The VelocityEngine is configured ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.