volicity 自定义指令 Directive 并获取ApplicationContext

阅读更多

背景说明:在基于spring MVC、volicity的WEB项目中,需要在volicity页面中读取远程配置信息(zookeeper)。

 

第一步:编写读取远程配置信息工具类(具体不做说明)

 

详情可参阅:http://timerbin.iteye.com/blog/2252372

 

第二步:编写自定义指令(Directive)

 

package cn.timerbin.util;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.ASTBlock;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import com.sun.el.parser.AstString;

public class ConfigTool extends Directive {
	
	private static final Log logger = LogFactory.getLog(ConfigTool.class);
	
	private static final String  MACRO_TAG_NAME="config";
	
	private static final int MACRO_TAG_TYPE = 2;
	//在spring上下文中获取依赖BEAN
	private static ZookeeperUtil zookeeperUtil =  (ZookeeperUtil) ApplicationContextUtil.getApplicationContext().getBean(ZookeeperUtil.class);
	private SimpleNode simpleNode = null;
	private  String defauleValue="timerBin";
	 
	@Override
	public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
	    String value = null;
		for(int i=0,j=node.jjtGetNumChildren();i 
  

 

 

第三步:定义获取spring 上下文 applicationContext的工具类

 

package cn.timerbin.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextUtil implements ApplicationContextAware {

	private static ApplicationContext context;
	
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.context=context;
	}
 
	public static ApplicationContext getApplicationContext(){
		return context;
	}
}

 

 

第四步:将自定义指令和自定义applicationConext的工具类定义到spring配置文件中

 





	
	
	
		
			cn.timerbin.util.ConfigTool
		
	


 其中velocityConfigurer常用的配置如下所示:

resourceLoaderPath:页面所放路径

configLocation:模板的配置参数信息其实与velocityProperties可以二选一来定义

velocityProperties

---userdirective:自定义指令

 

----velocimacro.library:定义宏的绑定仓库地址

其中配置较多可参阅:http://biz.163.com/0000/05/0226/15/1DHBTUKK000017JV.html

 

第五步:在volicity的页面VM中使用自定义指令

#config("zookeeper-key-name")

 

当然自定义指令中可以传输多个值。

 

注:以上配置只是提供了简单的思路,望各位在应用到自己项目中时请自行考虑安全问题(推荐签名方式传值)。

 

 

 

你可能感兴趣的:(Directive,自定义,Volicity,上下文)