---
title: "velocity模板问题"
author: "LSQ6063"
date: "2010-09-03T21:29:06Z"
tags: ["Cache", "velocity"]
categories: ["编程语言"]
slug: "velocity"
draft: false
lastmod: "2010-09-03T21:29:06Z"
id: 754936
url: "https://lsq6063.iteye.com/blog/754936"
---

今天很不幸又看到线上一个故障，又是因为在velocity模板中，foreach循环里set临时变量碰到null的问题

```
#foreach($x in $list)  ## 1
   #set ($temp = $x)  ## 2 设置临时变量的值
   $temp                   ## 3 输出临时变量的值
#end                        ## 4
```

 

在行2的地方，如果设置的值$x 为null，  
这时候$temp的值不会被重置，而是保留为循环中上一次赋的值！！

这个问题，出现过好几次，导致不同的故障，我搜索了一下我们的confluence，发现其它也出现过

原因很简单，因为现在的velocity版本里，为了兼容老的版本，默认是不允许在循环中设置null值给临时变量

解决办法很简单，在velocity.properties里加入directive.set.null.allowed = true，具体到我们的环境里，就是

```
        <service name="VelocityService" class="com.alibaba.service.velocity.DefaultVelocityService" earlyInit="true">
            <property name="file.resource.loader.path" value="/templates/esite"/>
            <property name="file.resource.loader.cache" value="true"/>
            <property name="directive.if.tostring.nullcheck" value="false"/>
            <property name="directive.set.null.allowed" value="true"/>
           .......
         </service>
```

 

这下，世界清净了。

 

 

--摘自一位同学处理故障