也可以用if…else标签,来判断输出 如果需要其他更确切的变量,可以去查看freemarker的标签大全。
配置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的测试项目