Velocity 自定义库加载优化

一、属性说明

        Velocimacro 属性

velocimacro.library – 是一个逗号分隔的所有Velocimacro 模板库的列表。

        默认情况下, Velocity 搜寻一个单一的库VM_global_library.vm.。预先配置的模板路径用来查找Velocimacro 库。


二、目的 

        忧化Velocity模板加载,减少过多的重复配置工作。

        例如:

需要加载多个模板写法如下:

<span style="white-space:pre">	</span>    velocimacro.library=macros/a.vm,macros/b.vm,macros/c.vm,macros/d.vm
        

忧化后:不需要再手动添加一个新模板就去修改配置文件,而直接交给自己写的监听器实现


三、实现

        web.xml配置listener程序启动,容器启动之前加载

<span style="white-space:pre">	</span><listener>
		<listener-class>cn.com.InitVelocityContextListener</listener-class>
	</listener> 
       

编写Listener类

        

public class InitVelocityContextListener implements ServletContextListener {

	private Logger logger = Logger.getLogger(this.getClass());
	
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		long startTime = System.currentTimeMillis();
		logger.info("-----------初始化velocity模板加载开始------------");

		// 获取项目路径
		String filePath = getClass().getResource("/").getPath();
		
		File file = new File(filePath);
		// 读取指定文件下所有需要加载模板
		String path = file.getParentFile().getPath() + File.separator + "velocity"+File.separator+"macros";
		
		// 读取Velocity需要加载的模板页面名称
		String velocimacroLibraryValue = getReadFileName(path);
		
		if(velocimacroLibraryValue!=null && !velocimacroLibraryValue.equals("")){
			// 存入至properties文件
			try {
				String propertieFilePath = file.getParentFile().getPath() + File.separator +  "velocity.properties";
				Properties properties = new Properties(); 
				OutputStream out = new FileOutputStream(new File(propertieFilePath));
	
				properties.setProperty("velocimacro.library", velocimacroLibraryValue);
				properties.store(out, null);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		long endTime = System.currentTimeMillis();
		logger.info("-----------初始化velocity模板加载结束!耗时:"+(endTime-startTime)+" s------------");
	}
	
	/**
	 * 读取文件夹下所有文件名
	 * @param path
	 * @return
	 */
	private static String getReadFileName(String path){
		File file = new File(path);
		StringBuilder sb = new StringBuilder();
		
		File[] array = file.listFiles();
		for (int i = 0; i < array.length; i++) {
			if(array[i].isFile()){
				sb.append("macros/"+array[i].getName()+",");
			}
		}
		return sb.toString().substring(0,sb.toString().length() - 1);
	}

	
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值