Freemarker 空值处理

来源:互联网 发布:网络蛋糕店 编辑:程序博客网 时间:2024/05/06 22:43
如果empty标签没有在servlet中添加key或者值为null,会报错 empty Value Expression newTag is undefined。有人说这是个好的控制错误的机制,但本人不这么认为,因为空值太常见了,谁知道什么时候里面就成空值了?每个变量理论上都有可能。 

难道每个变量都要加入一个判断?就像struts中丑陋的<empty>标签?既然是模板引擎,就要灵活,何必来那么多限制? 

还好,freemarker至少提供了解决办法,否则我只好选择其它引擎了。 

freemarker中空值的多种处理方法: 

1.按照freemarker的规范,老老实实的判断是否有空值,有空值怎么处理。这在某种时候是有用的。格式:${empty!"EmptyValue of fbysss"} 
比如值为空时,你可以给出一个友好的说明,但是很多的变量都要这么说明,未免太麻烦了。 

2.<#escape x as x!""></#escape>可以对所有的变量进行空值处理,这里是全部替换为空字符串。当然也可以替换为其它字符串。 
如果其中某些变量不需要这种替换,可以加入<#noescape></#noescape>标签。 

3.属性配置方法: 
配置classic_compatible=true可以满足一般需要。默认情况变量为null则替换为空字符串,如果需要自定义,写上${empty!"EmptyValue of fbysss"}的形式即可 

a.通过Configuration设置。Configuration cfg = new Configuration(); cfg.setClassicCompatible(true);//设置属性 

b.通过Eviroment设置。 
   Environment env = template.createProcessingEnvironment(root, out); 
   env.setClassicCompatible(true); 

c.通过ftl设置:在ftl前加入<!--#setting classic_compatible=true-->; 

d.通过Spring配置文件设置 
<bean id="freemarkerConfig" 
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 
  <property name="freemarkerSettings"> 
    <props> 
      <prop key="classic_compatible">true</prop> 
    </props> 
  </property> 
</bean> 

e.class目录下添加freemarker.properties文件:加入classic_compatible=true 
(需要struts2或spring)