Velocity 自定义库加载优化

来源:互联网 发布:淘宝虚拟试衣间关了吧 编辑:程序博客网 时间:2024/05/18 18:16

一、属性说明

        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());@Overridepublic void contextDestroyed(ServletContextEvent arg0) {}@Overridepublic 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);}}

0 0