freemarker之空值处理解决方案
1.使用判断标签
${user.name?if_exists} //判断存在则输出,反之不输出
${user.name!default("默认值")} or ${name!"默认值"} // 判断存在则输出,反之输出默认值
${datename?string('yyyy-MM-dd')} //日期格式
也可以用if…else标签,来判断输出
如果需要其他更确切的变量,可以去查看freemarker的标签大全。
2.使用escape和noescape标签
- 可以对所有的变量进行空值处理,这里是全部替换为默认值。
需要设置默认值(可以设置为空“”):
<#escape x as x!"默认值">
<span>账号</span>${user.id}
<span>姓名</span>${user.name}
</#escape>
- 不需要设置默认值(对空值不处理):
<#noescape>
<span>账号</span>${user.id}
<span>姓名</span>${user.name}
</#noescape>
3.属性配置方法:
配置classic_compatible属性为true,可以满足一般需要。默认情况变量为null则替换为空字符串。但注意这个日期的空值还是需要使用方法1。
- 1、通过Configuration设置。这个设置可以在构造器或者ini方法使用。
private Configuration configuration = null; //解释Configuration
//构造函数
public FreeMarkerHandler(){
configuration = new Configuration();
//输出的数据默认的编码类型
configuration.setDefaultEncoding("utf-8");
//方法一:处理空值
configuration.setClassicCompatible(true);
}
- 2、通过Eviroment设置。
//合并数据模型和模版,并将结果输出到out中
Environment env = template.createProcessingEnvironment(dataMap, out);
env.setClassicCompatible(true);
env.process();
- 3、通过ftl设置:在ftl的第一行前添加
<#setting classic_compatible=true>
- 4、Spring项目,通过配置文件设置
因为我的就是Spring项目,所以用的就是这种方法,把所有配置都贴出来,大家可以参考一下。
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!-- 指定FreeMarker模板文件目录 -->
<property name="templateLoaderPath" value="/WEB-INF/views/" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="defaultEncoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="boolean_format">true,false</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="number_format">0.######</prop>
<prop key="whitespace_stripping">true</prop>
<!--空值处理-->
<prop key="classic_compatible">true</prop>
<prop key="auto_import">/commons/header.ftl as p,/commons/storejoininheader.ftl as sp,/commons/store_joinin_left.ftl as sl
</prop>
</props>
</property>
</bean>
- 5、使用freemarker.properties文件配置
添加属性classic_compatible=true
//加载并设置freemarker.properties
Properties p = new Properties();
p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));
configuration.setSettings(p);
e1.printStackTrace();
我写了一个简单的demo,放在码云。有兴趣的童鞋可以下来看看,测试一下
freemarker的测试项目