解决ftl空值的问题

在项目中需要使用freemarker技术,但是在使用ftl文件导出word文档时,如果传入空值导出就会失败。

${empty}
如果empty标签没有在servlet中添加key或者值为null,会报错 empty Value Expression newTag is undefined。

以下几种方法能够解决空值的问题:

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),

 将${user.memo}改写成 ${(user.memo}!}或者${(user.memo}?if_exists}这种方法也是可以的。


猜你喜欢

转载自blog.csdn.net/shiboyuan0410/article/details/79915210
今日推荐