2007年6月11日星期一

源码研究:struts2中的freemaker的模板加载

初在struts2中若采用freemaker模板引擎,对于模板的加载方式有所疑惑,为什么在webapp下的模板可以覆盖在struts2默认的模板,是怎样加载存在classpath下的模板文件?
下面我找到了他的核心代码:FreemarkerManager.java中的方法:
/**
* The default template loader is a MultiTemplateLoader which includes
* a ClassTemplateLoader and a WebappTemplateLoader (and a FileTemplateLoader depending on
* the init-parameter 'TemplatePath').
*


* The ClassTemplateLoader will resolve fully qualified template includes
* that begin with a slash. for example /com/company/template/common.ftl
*


* The WebappTemplateLoader attempts to resolve templates relative to the web root folder
*/
protected TemplateLoader getTemplateLoader(ServletContext servletContext) {
// construct a FileTemplateLoader for the init-param 'TemplatePath'
FileTemplateLoader templatePathLoader = null;

String templatePath = servletContext.getInitParameter("TemplatePath");//首先检查servlet的参数中是否指定了模板目录的绝对路径,在特//殊需求下,也许你会用到这个配置方法
if (templatePath == null) {
templatePath = servletContext.getInitParameter("templatePath");
}

if (templatePath != null) {
try {
templatePathLoader = new FileTemplateLoader(new File(templatePath));
} catch (IOException e) {
log.error("Invalid template path specified: " + e.getMessage(), e);
}
}

// presume that most apps will require the class and webapp template loader
// if people wish to
//在这里返回个

MultiTemplateLoader,请注意templatePathLoader,WebappTemplateLoader,StrutsClassTemplateLoader的顺序,
//模板的加载过程是从前往后的,如果找到了相应的模板就不在继续查找了,故而在webapp下的templeate可以覆盖struts默认的模板,
//当然你也可以自己实现一个freemanager的扩展类,来实现自己特殊的加载方式,例如从另一个模板服务器记载等....

return templatePathLoader != null ?
new MultiTemplateLoader(new TemplateLoader[]{
templatePathLoader,
new WebappTemplateLoader(servletContext),
new StrutsClassTemplateLoader()
})
: new MultiTemplateLoader(new TemplateLoader[]{
new WebappTemplateLoader(servletContext),
new StrutsClassTemplateLoader()
});
}


没有评论: