运行velocity的examples的examples.app_example2,
public class Example2
{
public static void main( String args[] )
{
try
{
Velocity.init();
}
catch(Exception e)
{
System.out.println("Problem initializing Velocity : " + e );
return;
}
VelocityContext context = new VelocityContext();
context.put("name", "Velocity");
context.put("project", "Jakarta");
StringWriter w = new StringWriter();
try
{
Velocity.mergeTemplate("example2.vm", "ISO-8859-1", context, w );
}
catch (Exception e )
{
System.out.println("Problem merging template : " + e );
e.printStackTrace();
}
System.out.println(" template : " + w );
String s = "We are using $project $name to render this.";
w = new StringWriter();
try
{
Velocity.evaluate( context, w, "mystring", s );
}
catch( ParseErrorException pee )
{
System.out.println("ParseErrorException : " + pee );
}
catch( MethodInvocationException mee )
{
System.out.println("MethodInvocationException : " + mee );
}
catch( Exception e )
{
System.out.println("Exception : " + e );
}
System.out.println(" string : " + w );
}
}
出现错误: org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'example2.vm'
修正:
Velocity.init();
为:
Properties properties = new Properties();
String basePath = "src/examples/app_example2";
// 设置模板的路径
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);
Velocity.init(properties);