velocity学习(3)--velocity.properties 配置文件

velocity.properties 配置文件

apache 在 velocity-1.7.jar 的 org.apache.velocity.runtime.defaults 下提供了一个默认的配置文件 velocity.properties,同目录下的 directive.properties 定义的是 velocity 的常用指令(#set 等),我们可以打开观看其具体实现,这里不多做解释。在自定义我们的配置文件时,可以以默认配置文件 velocity.properties 作为参考。而自定义的配置文件通常放在 WEB-INF 目录下。我们需要在 web.xml 中,对 org.apache.velocity.tools.view.VelocityViewServlet 我加一个参数指定 velocity.properties 的路径,如下所示:

web.xml

<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>
    org.apache.velocity.tools.view.VelocityViewServlet
</servlet-class>
<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>

当 VelocityViewServlet 拦截到对.vm 的请求时,会自动加载此配置文件,初始化模板引擎和 velocity 上下文。这里我们主要了解几个重要的配置,所有配置的详细注释均可在velocity-1.7.jar 内默认配置文件中找到。

解决乱码

如果不配置 velocity 的编码,velocity 将使用默认的 ISO-8859-1,这通常不是我们想要的结果,可以在 velocity.properties 中进行编码的配置:

input.encoding=utf-8
output.encoding=utf-8

这样配置后,velocity 就可以在页面正常输出中文了。如果在实际使用中,配置后依然无法正常输出中文,则应考虑 http 请求/数据库等部分是否正确配置。

foreach 计数器配置

directive.foreach.counter.name = velocityCount
directive.foreach.counter.initial.value = 1
directive.foreach.maxloops = -1
directive.foreach.iterator.name = velocityHasNext

这里可以对 foreach 迭代的计数器变量名称,判断迭代是否完成的变量名称进行配置,还可以对计数器初始值和最大值进行配置。

#parse()解析深度

默认配置文件中定义了一个解析深度。通常不需更改,也几乎不会用到,但一旦遇到超过解析深度的情况,我们应该知道存在这个配置。

directive.parse.max.depth = 10

宏定义相关

配置文件中可以指定一个宏定义库,以及宏定义的嵌套深度。

velocimacro.library = VM_global_library.vm
velocimacro.max.depth = 20

启用严格模式

velocimacro.arguments.strict = false

日志

运行 velocity 引擎我们会发现多出一个 velocity.log 文件,这个就是 velocity 引擎的运行日志。默认文件名为 velocity.log。关闭日志只需将 runtime.log.logsystem.class 设定为 org.apache.velocity.runtime.log.NullLogChute

runtime.log.logsystem.class =
org.apache.velocity.runtime.log.AvalonLogChute,org.apache.velocity.runtime.l
og.Log4JLogChute,org.apache.velocity.runtime.log.CommonsLogLogChute,org.apac
he.velocity.runtime.log.ServletLogChute,org.apache.velocity.runtime.log.JdkL
ogChute
runtime.log = velocity.log

猜你喜欢

转载自blog.csdn.net/wu2374633583/article/details/80143873