当需要从一个指定的目录提取模板文件时(默认为当前目录),你可以这样做 :
import java.util.Properties;
...
public static void main( String args[] )
{
/* first, we init the runtime engine. */
Properties p = new Properties();
p.setProperty("file.resource.loader.path", "/opt/templates");
Velocity.init( p );
/* lets make a Context and put data into it */
...
这样,Velocity在需要时,将自动到/opt/templates目录下查找模板文件,如果有问题可以查看velocity.log中所记录的出详细出错信息。它会帮你有效的消息错误.
8.Application Attributes
Application Attributes (应用程序属性)是和VelocityEngine 的运行时实例(Runtimeinstance)相关联的,名-值对(name-value pairs)格式的参数,可用来存运RuntimeInstance时的信息.
设计这个功能的目标是Velocity程序需要与应用层或用户定制部分(如日志,资源,装载器等)通信.
The Application Attribute API is very simple. From the application layer,在 VelocityEngine 和 Velocity classes 中都有如下命令:
public void setApplicationAttribute( Object key, Object value );
这里的key与value的设置没有任何限制,可以在程序运行中设置,这是不同与Velocity的init()调用的.
内部程序可以通过接口 RuntimeServices 如下的命令来取得这些参数:
public Object getApplicationAttribute( Object key ):
9.EventCartridge and Event Handlers(事件分发和处理)
1.Event Handlers
从Velocity1.1版本起,加入了良好的事件处理机制. 你可将自己的事件处理器类注册给事件分发器(EventCartridge) , 事件分发器实际上扮演着Velocity engine在运行时访问事件处理器(event handlers)的一个代理的角色。目前,有3种Velocity系统定义的事件可以被处理,它们都位与包org.apache.velocity.app.event 中.
org.apache.velocity.app.event.NullSetEventHandler
当模板中#set() 指令关联的是一个空值时, 这是很常见的一个问题. The NullSetEventHandler 事件处理器可以让你决定如何处理,其接口代码如下.
public interface NullSetEventHandler extends EventHandler
{
public boolean shouldLogOnNullSet( String lhs, String rhs );
}
org.apache.velocity.app.event.ReferenceInsertionEventHandler
public interface ReferenceInsertionEventHandler extends EventHandler
{
public Object referenceInsert( String reference, Object value );
}
org.apache.velocity.app.event.MethodExceptionEventHandler
当用户数据对象中的某个命令出错时, 实现了 MethodExceptionEventHandler接口的事件处理器将被调用以获得具体的命令名字和Exception对象. 事件处理器也可以重组一个有效的对象返回(一般用于统一的异常处理), 或向它的父类throws一个new Exception, MethodInvocationException接口如下:
public interface MethodExceptionEventHandler extends EventHandler
{
public Object methodException( Class claz, String method, Exception e )
throws Exception;
}
2.Using the EventCartridge使用事件分发器
可以直接使用一个事件分发器(EventCartridge),如下例程在org.apache.velocity.test.misc.Test中:
...
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import org.apache.velocity.app.event.NullSetEventHandler;
...
public class Test implements ReferenceInsertionEventHandler,
NullSetEventHandler,
MethodExceptionEventHandler
{
public void myTest()
{
....
/*
* now, it's assumed that Test implements the correct methods to
* support the event handler interfaces. So to use them, first
* make a new cartridge