初学Velocity,想写个VelocityTool类实现以相对路径方式嵌入动态页面,思路大致与http://www.oschina.net/code/snippet_12_694中一样,因为新版中init(Object arg0)方法已经Deprecated了,换用configure(Map props)(见http://velocity.apache.org/tools/devel/upgrading.html最下面和http://velocity.apache.org/tools/devel/creatingtools.html),代码如下:
import java.util.Map;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.tools.view.ViewContext;
public class VelocityTool {
protected VelocityContext velocity;
public void configure(Map props) {
Object obj = props.get("velocityContext");
if (obj instanceof ViewContext) {
ViewContext viewContext = (ViewContext) obj;
velocity = (VelocityContext) viewContext.getVelocityContext();
}
}
public String cur_templete() {
return velocity.getCurrentTemplateName();
}
}
我使用的Velocity和VelocityTools的版本都是最新的。
但是运行时出现错误:
Caused by: java.lang.ClassCastException: org.apache.velocity.tools.view.context.ChainedContext cannot be cast to org.apache.velocity.VelocityContext
可见从获得的ViewContext是ChainedContext类型了,不能强制转换为 VelocityContext类型。
我又换了老方法,使用init(Object arg0)方法,Copy红薯的代码来用,也不行,错误是一样的,都是ChainedContext不能强制转换为 VelocityContext。
各位高手,请问有办法解决吗?或者有其他办法可以达到这个目的吗?在使用最新版Velocity和VelocityTool的情况下。