⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 eventhandler.java

📁 《基于Eclipse的开源框架技术与实战》[第11章]随书源码
💻 JAVA
字号:
package com.free.vtl.event;

import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import org.apache.velocity.app.event.NullSetEventHandler;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.context.Context;

/**
 * <p>Title: Eclipse Plugin Development</p>
 * <p>Description: Free download</p>
 * <p>Copyright: Copyright (c) 2006</p>
 * <p>Company: Free</p>
 * @author gan.shu.man
 * @version 1.0
 */

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("./WEB-INF/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);
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -