2007-06-04

Velocity找不到模版文件的问题解决

关键字: Veloctity

Veloctity默认采用文件加载的方式(FileResourceLoader)来加载模版文件,这就要求模版文件放在系统目录下,比如system32下,或者给出绝对路径,为了让其从class目录下开始查找模版文件,需要将其加载方式指定为按类的方式(ClasspathResourceLoader )进行加载,因此要改写velocity.properties文件:classpath.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

在eclipse plugin中使用velocity的注意事项
有时候为了方便管理,我们会将所有jar包统一放在同一个plugin工程里面,这样在使用velocity的时候,定义的模版文件也必须放在jar包所在工程,否则会出现找不到的资源的异常,这个主要跟类加载器有关,velocity的getTemplate()方法将使用模版加载器类(如ClasspathResourceLoader)的类加载器来取得模版文件,也就是ClasspathResourceLoader.getClassLoder().getResourceAsStream("template path"),因为加载器类和模版文件不在同一个工程里面,因此二者对应的是两个不同的类加载器,找不到资源也就不难理解了。


评论
macrochen 2007-10-17
不是修改源代码,你把原来的velocity.properties文件copy出来并修改classpath.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader,然后在某个初始化类里面这样写:
InputStream in = getClass().getResourceAsStream("velocity.properties");
		if (in != null) {
			Properties properties = new Properties();
			try {
				properties.load(in);
				Velocity.init(properties);
			} catch (Exception e) {
				ExceptionHandler.processException(e);
			}
		}

就ok了
myyate 2007-10-17
请问:修改velocity.properties的话,你的意思是修改源代码了?除了给定绝对路径的方法和这个方法,还有其他方法吗?为什么classpath.resource.loader.class 在程序中替代不了呢?
发表评论

您还没有登录,请登录后发表评论