객체는 Velocity 템플릿의 컨텍스트에서 설정할 수 있습니다. 그런 다음 해당 객체를 이름을 사용하여 템플릿에서 호출 할 수 있습니다.
템플리트가 VelocityJavaMethodExample Object에서 hello 메소드를 호출하기를 원한다고 가정 해보자.
public class VelocityJavaMethodExample {
public String hello( String input ){
return "Hello " + input;
}
}
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();
}
}
}
Esto es una prueba
자바 메소드 호출 : $MyVariable.hello( $input )
Esto es una prueba 자바 메소드 호출 : Hello World