example.vm文件编码如下:
##开始
Hello from $name in the $project project.
#set( $this = "TestVelocity")
$this is the best great!
#foreach( $names in $lister )
$names is very great!
#end
#set( $condition = true)
#if ($condition)
The condition is true!
#else
The condition is false!
#end
velocity.properties文件内容如下:
runtime.log = velocity_example.log
将上述两个文件放入工程目录下的新建文件夹vm里,然后可以设置路径,在下面的java文件中修改相应的路径就可以了。
java文件的编码
package app.example;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import java.io.*;
import java.util.ArrayList;
public class Example
{
public Example(String templateFile)
{
try
{
Velocity.init("vm\\example\\velocity.properties ");
VelocityContext context = new VelocityContext();
context.put("lister", getNames());
context.put("name", "Velocity;;;;;;;");
context.put("project", "Jakarta....");
StringWriter sw = new StringWriter();
String s = "$lister";
Velocity.evaluate( context, sw, "mystring", s );
System.out.println(sw);
Template template = null;
try
{
template = Velocity.getTemplate(templateFile);
}
catch( ResourceNotFoundException rnfe )
{
System.out.println("Example : error : cannot find template " + templateFile );
}
catch( ParseErrorException pee )
{
System.out.println("Example : Syntax error in template " + templateFile + ":" + pee );
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
if ( template != null)
template.merge(context, writer);
writer.flush();
writer.close();
}
catch( Exception e )
{
System.out.println(e);
}
}
public static ArrayList<String> getNames()
{
ArrayList<String> list = new ArrayList<String>();
list.add("ArrayList element 1");
list.add("ArrayList element 2");
list.add("ArrayList element 3");
list.add("ArrayList element 4");
return list;
}
public static void main(String[] args)
{
Example t = new Example("vm\\example\\example.vm ");
//注释部分为另一种用法,效果类似。
/* Velocity.init();
VelocityContext context = new VelocityContext();
context.put("name", "Velocity;;;;;;;");
context.put("project", "Jakarta....");
context.put("lister", getNames());
StringWriter sw = new StringWriter();
Velocity.mergeTemplate("vm\\example\\example.vm", "ISO-8859-1", context, sw );
String a = sw.toString();
System.out.println(a);*/
}
}
运行结果(控制台输出)如下:
[ArrayList element 1, ArrayList element 2, ArrayList element 3, ArrayList element 4]
Hello from Velocity;;;;;;; in the Jakarta.... project.
TestVelocity is the best great!
ArrayList element 1 is very great!
ArrayList element 2 is very great!
ArrayList element 3 is very great!
ArrayList element 4 is very great!
The condition is true!