首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Velocity自定义授命(函数)

2012-10-28 
Velocity自定义指令(函数)使用velocity的时候,我们可能需要实现自定义的函数,类似: #somefun() 这个函数可

Velocity自定义指令(函数)
使用velocity的时候,我们可能需要实现自定义的函数,类似:

#somefun()

这个函数可能是需要做一些业务代码,或者往context存取变量,或者可以向页面输出html代码。

假如我们要写一个输出hello xxx的函数,其中xxx是从context中取出的变量值,首先要在velocity.properties中添加一个:

userdirective=me.bwong.vm.HelloFun,...others

这一行告诉velocity引擎,在我的工程中有一个velocity函数,这个函数实现类是me.bwong.vm.HelloFun,这个类需要实现接口:org.apache.velocity.runtime.directive.Directive,参考如下代码:

public class HelloFun extends Directive {    
@Override
    public String getName() {
        return "hellofun";
    }
@Override
    public int getType() {
        return LINE;
    }    
@Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
         return true;
    }
}

getName接口用来告诉velocity这个函数名是什么,也就是页面上调用这个函数的名称,比如#hellofun();

getType接口用来告诉velocity这个函数类型,可以是行也可以是块函数;

render接口用来输出html代码,当然也可以不输出,如果需要输出,则使用入参的writer.write("some html"),context是当前velocity的容器,可以存取变量,比如在页面上使用#set($name="bwong"),可以通过context.get("name")取出"bwong",node里面可以取出调用这个函数时的入参,比如#hellofun("a"),通过node.jjtGetChild(0).value(context)取出"a",所以:

writer.write("hello " + node.jjtGetChild(0).value(context));

就可以输出"hello xxx",xxx是调用这个函数时的入参。

欢迎光临我的独立博客http://bwong.me

热点排行