Velocity中加载vm文件的三种方式(也可以参考demo文件夹下的例子对照)
Velocity中加载vm文件的三种方式:
方式一:加载classpath目录下的vm文件
Properties p = new Properties();
p.put("file.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(p);
...
Velocity.getTemplate(templateFile);
方式二:根据绝对路径加载,vm文件置于硬盘某分区中,如:d:\\tree.vm
Properties p = new Properties();
p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "d:\\");
Velocity.init(p);
...
Velocity.getTemplate("tree.vm");
方式三:使用文本文件,如:velocity.properties,配置如下:
input.encoding = UTF-8
file.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
再利用如下方式进行加载
Properties p = new Properties();
p.load(this.getClass().getResourceAsStream("/velocity.properties"));
Velocity.init(p);
...
Velocity.getTemplate(templateFile);
方法四: org.apache.velocity.runtime.resource.loader.URLResourceLoader
2.加载远程文件的问题
解决方案1.
http://mail-archives.apache.org/mod_mbox/velocity-user/200211.mbox/%3CB9F95F44.1AB00%25zodiac@holoweb.net%3E<!--[if !supportNestedAnchors]--><!--[endif]-->
解决方案2
http://badqiu.javaeye.com/blog/691617
public class ApplicationContext extends AbstractInterceptor{
private static final long serialVersionUID = 5728757263270691902L;
private static Logger log = Logger.getLogger(ApplicationContext.class);
@Override
public String intercept(ActionInvocation ai) throws Exception {
log.info("Oh,yeah. I'm intercepting.");
try{
Map<String, Object> application = ai.getInvocationContext().getApplication();
Object ac = application.get("ac");
Object httpInclude = application.get("httpInclude");
log.info(application.get("httpInclude"));
if(null==ac && null!=application)
application.put("ac", new AgencyConstants());
if(null==httpInclude&&null!=application)
application.put("httpInclude",new-HttpInclude(ServletActionContext.getRequest(), ServletActionContext.getResponse()));
if(null==application)
return Action.ERROR;
return ai.invoke();
}catch(Exception e){
log.error(e.getLocalizedMessage());
e.printStackTrace();
return Action.ERROR;
}
}
}
参考:
http://velocity.apache.org/engine/releases/velocity-1.5/developer-guide.html
http://hailinhe1986-163-com.javaeye.com/blog/657211
Other Demo
http://www.javaranch.com/journal/2004/03/Velocity-AnIntroduction.html