使用#parse的速度,文件不存在

时间:2009-07-14 10:43:37

标签: velocity template-engine

我们使用Velocity来模拟几个不同环境的配置文件,这个过程非常有效,但我有一个关于解析不存在的文件的快速问题。

我的问题是: 在解析文件之前如何检查文件是否存在?

因此,在示例中,文件default.user.properties可能合法地不存在,如果不存在,则不会解析文件的其余部分。

#parse("./default.user.properties")

我知道一个解决方案是确保文件始终存在,但如果我不必这样做会很好。

提前致谢。

3 个答案:

答案 0 :(得分:4)

刚刚用弹簧和速度做到了这一点:

我在获取速度以获取事件处理程序时遇到问题,最后在servlet xml文件中指定它:

<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="WEB-INF/templates"/>
        <property name="velocityPropertiesMap">
            <map>
                <entry key="eventhandler.include.class"><value>com.velocity.events.OptionalIncludeEventHandler</value></entry>
            </map>
        </property>
    </bean>

它根本不接受我将它放在属性文件中 - 它会实例化该类,但不会将其注册为事件监听器。非常令人沮丧。

这个类本身很简单,从现有的速度类“org.apache.velocity.app.event.implementIncludeNotFound”中脱颖而出。现有的速度实现检查文件是否存在,如果不存在则返回可配置的替代(默认值:notfound.vm)。

我的情况完全相同,但如果文件不存在则返回null,导致解析器跳过此include / parse指令:

public class OptionalIncludeEventHandler implements IncludeEventHandler, RuntimeServicesAware {

    private RuntimeServices rs;

    @Override
    public void setRuntimeServices(RuntimeServices rs) {
        this.rs = rs;
    }

    @Override
    public String includeEvent(String includeResourcePath, String currentResourcePath, String directiveName) {
        return rs.getLoaderNameForResource(includeResourcePath) != null ? includeResourcePath : null;
    }

}

像魅力一样。

希望它有用。

答案 1 :(得分:1)

一种新类型的事件处理程序“IncludeEventHandler”。这允许开发人员定义一个类(实现IncludeEventHandler),每次评估#parse或#include时都会调用它。事件处理程序的目的是检查模板是否存在,如果没有,则为调用代码设置错误标志。 查看文档以获取更多信息,但我自己没有测试过

答案 2 :(得分:1)

我使用的解决方案是创建一个检查模板存在的实用方法,即

public synchronized boolean templateExists(String templateFilename) {
    Boolean templateExists = this.templateExistsCache.get(templateFilename);
    if (templateExists != null) {
        return templateExists;
    }
    String absoluteFilename = this.request.getSession().getServletContext().getRealPath(
            "/WEB-INF/templates/" + templateFilename);
    File templateFile = new File(absoluteFilename);
    templateExists = templateFile.exists();
    this.templateExistsCache.put(templateFilename, templateExists);
    return templateExists;
}

private Map<String, Boolean> templateExistsCache = new HashMap<String, Boolean>();

来自

https://github.com/okohll/agileBase/blob/master/gtpb_server/src/com/gtwm/pb/model/manageData/ViewTools.java