값 null은 Velocity에 의해 부울 값 false 로 테스트됩니다.
This is a test
#if( !$test )
Test is null
#end
#if( $test == true )
Test is NOT null
#end
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 VelocitySimple4 {
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( "example4.vm" );
// Create the
VelocityContext context = new VelocityContext();
context.put("test", null);
try {
// Create the output file
Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( new File( sourceDirectory + "example4.txt" ) ), "UTF8") );
t.merge( context, out);
out.close();
} catch ( Exception e ){
e.printStackTrace();
}
}
}
This is a test
Test is null
코드는 먼저 파일 리소스 로더를 사용하여 VelocityEngine 을 초기화합니다. 유효한 값 테스트는 값이 null 인 컨텍스트에서 설정되고 템플릿은 컨텍스트와 병합되며 출력은 example4.txt 파일에 저장됩니다.