velocity的默认配置路径

查看了下velocity初始化的源码,发现了以下几句:

    protected static final String TOOLBOX_KEY = "org.apache.velocity.toolbox";

    /**
     * This is the string that is looked for when getInitParameter is
     * called ("org.apache.velocity.properties").
     */
    protected static final String INIT_PROPS_KEY = "org.apache.velocity.properties";

    /**
     * Default toolbox configuration file path. If no alternate value for
     * this is specified, the servlet will look here.
     */
    protected static final String DEFAULT_TOOLBOX_PATH ="/WEB-INF/toolbox.xml";

    /**
     * Default velocity properties file path. If no alternate value for
     * this is specified, the servlet will look here.
     */
    protected static final String DEFAULT_PROPERTIES_PATH = "/WEB-INF/velocity.properties";


很明显,这些是velocity默认的配置文件toolbox.xml和velocity.properties的路径和key

在velocity初始化时会默认去找以上两个路径,如果没有找到,会加载他自带的文件。

这两个路径在什么时候会加载呢?

/**
* Looks up an init parameter with the specified key in either the
* ServletConfig or, failing that, in the ServletContext.
*/
protected String findInitParameter(ServletConfig config, String key)
{
    // check the servlet config
    String param = config.getInitParameter(key);

    if (param == null || param.length() == 0)
    {
        // check the servlet context
        ServletContext servletContext = config.getServletContext();
        param = servletContext.getInitParameter(key);
    }
    return param;
}

从上面这段代码看出,velocity会从servletconfig和servletcontext的初始化参数中加载,这就意味着你要把参数写在web.xml的servlet配置中,<init-param></init-param>就是你该写的地方了,呵呵,简单吧。例如:

<servlet>
    <servlet-name>velocity</servlet-name>
    <servlet-class>
        org.apache.velocity.tools.view.servlet.VelocityLayoutServlet
    </servlet-class>

    <init-param>
        <param-name>org.apache.velocity.toolbox</param-name>
        <param-value>/WEB-INF/toolbox.xml</param-value>
    </init-param>
    <init-param>
        <param-name>org.apache.velocity.properties</param-name>
        <param-value>/WEB-INF/velocity.properties</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
</servlet-mapping>

posted @ 2012-10-17 17:41  爱吃猫的鱼~  阅读(1024)  评论(0编辑  收藏  举报