Velocity的事件處理
Velocity提供了對模板解析過程事件的處理,用戶可以響應模板產生的事件。模板事件有設置模板變量、模板參數為空以及調用模板方法時出錯等。
要響應模板事件可以實現Velocity的接口,提供相應的處理。模板事件都繼承于“org.apache.velocity.app.event.EventHandler”接口,有如下幾個接口的實現:
1. ReferenceInsertionEventHandler:要實現的方法為referenceInsert,響應從模板上下文給模板變量賦值。
2. NullSetEventHandler:要實現的方法為shouldLogOnNullSet,響應當賦值的變量為空的事件。
3. MethodExceptionEventHandler:要實現的方法為methodException,響應當調用的方法拋出異常時的處理。
模板的事件提供了用戶代碼和模板引擎的交互的方式,為演示三種類型的模板事件,可以通過實例進行介紹,如例程9-10所示。
例程9-10 模板事件的處理
public class EventHandler implements ReferenceInsertionEventHandler,
NullSetEventHandler, MethodExceptionEventHandler {
public EventHandler(Context ctx) {
EventCartridge ec = new EventCartridge();
//添加模板事件的處理實例
ec.addEventHandler(this);
//添加模板上下文
ec.attachToContext(ctx);
}
/**
* 處理引用值的插件
* */
public Object referenceInsert(String reference, Object data) {
System.out.println("referenceInsert: " + reference + " data: " + data);
return data;
}
/**
* 處理空值
* @param lhs 被賦值變量
* @param rhs 將要賦的值
* */
public boolean shouldLogOnNullSet(String lhs, String rhs) {
System.out.println("Null:");
System.out.println("lhs:" + lhs + " rhs:" + rhs);
return true;
}
/**
* 處理模板調用方法拋出的異常
* @param cls 拋出異常的類
* @param method 拋出異常的方法
* @param e 拋出的異常
* */
public Object methodException(Class cls, String method, Exception e)
throws Exception {
return "An " + e.getClass().getName() + " was thrown by the " + method
+ " method of the " + cls.getName() + " class ["
+ e.getMessage() + "]";
}
public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/eventHandler.vm");
Context ctx = new VelocityContext();
ctx.put("person", "Joe");
ctx.put("exception", new ExceptionGenerator());
//設置異常處理類及上下文
EventHandler hdl = new EventHandler(ctx);
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}
public class ExceptionGenerator {
public String generate() throws Exception {
Random rnd = new Random();
int x = rnd.nextInt(5);
if (x == 2) {
throw new Exception("Unlucky!");
} else {
return "No Exception";
}
}
}
模板文件eventHandler.vm
#set($myNull1 = $testNull)
This is $person
$exception.generate()