你可以通过覆盖速度的FileResourceLoader类的FileResourceLoader,该类将Concat的WEB_APP_ROOT路径和路径项的速度CONFIGRATION:
public class WebAppFileResourceLoader extends FileResourceLoader {
private Logger log= LoggerFactory.getLogger(WebAppFileResourceLoader.class);
@Override
public void init(ExtendedProperties configuration) {
String webAppRootPath= (String) this.rsvc.getApplicationAttribute(WEB_APP_ROOT);
if (webAppRootPath!=null) {
Vector<String> pathsVector = configuration.getVector("path");
Vector<String> tempVector = new Vector<String>(pathsVector.size());
for (String path : pathsVector) {
log.debug("path:{}", path);
tempVector.add(webAppRootPath + File.separator + path);
}
configuration.clearProperty("path");
for (String path : tempVector) {
configuration.addProperty("path", path);
}
}
super.init(configuration);
}
如何获得WEB_APP_ROOT变量,我们可以把它当极速引擎INIT:
public class SpringVelocityEngineFactoryBean extends VelocityEngineFactory
implements FactoryBean<VelocityEngine>, InitializingBean, ResourceLoaderAware,ServletContextAware {
private VelocityEngine velocityEngine;
private ServletContext servletContext;
private Logger log= LoggerFactory.getLogger(SpringVelocityEngineFactoryBean.class);
@Override
protected VelocityEngine newVelocityEngine() throws IOException, VelocityException {
//inject servletContext to velocity runtime's applicationAttribute
VelocityEngine velocityEngine= new VelocityEngine();
velocityEngine.setApplicationAttribute(ServletContext.class.getName(), this.servletContext);
log.debug("webappRoot:{}",this.servletContext.getRealPath(""));
velocityEngine.setApplicationAttribute(WEB_APP_ROOT,this.servletContext.getRealPath(""));
return velocityEngine;
}
....
以这种方式,我无法加载模板文件,因为它无法找到根路径。因为我使用velocity来渲染一些html部分,只是不把速度视为渲染引擎。所以我发布我的这里的方式... – cleverpig 2015-01-08 03:36:40