问题场景:
SSM整合freemarker发送邮件时,因为发送的内容中有字段为空值。所以发生异常信息如下:
ERROR: freemarker.runtime - Error executing FreeMarker template
FreeMarker template error:
The following has evaluated to null or missing:
==> user [in template "include/header.ftl" at line 4, column 14]
----
Tip: If the failing expression is known to be legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing</#if>. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??
----
----
FTL stack trace ("~" means nesting-related):
- Failed at: #if user [in template "include/header.ftl" at line 4, column 9]
- Reached through: #include "/include/header.ftl" [in template "index.ftl" at line 6, column 1]
----
Java stack trace (for programmers):
----
freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...]
at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:131)
at freemarker.core.UnexpectedTypeException.newDesciptionBuilder(UnexpectedTypeException.java:77)
解决方案:
方案一,在网上搜索该问题时,有答案说在spring配置文件的freemarker注入时,加入 <prop key="classic_compatible">true</prop>,如下:
<bean id="MailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="host" value="smtp.163.com"></property>
<property name="username" value="1****@163.com"></property>
<property name="password" value="***"></property>
<property name="javaMailProperties">
<props>
<prop key="classic_compatible">true</prop>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
</bean>
上述方法,尝试依然未解决。可能是使用方法哪里有问题。
方案二:直接在freemarker的模板文件中加入<#setting classic_compatible=true>即Ok了,如下
<html>
<body>
<h3><font color="red">接口有错误!</font></h3>
<h6>Detail:</h6>
<div>
<p>测试时间:${runtime?datetime}</p>
<#setting classic_compatible=true>
<#list reportlist as report>
<font color="red"> ${report.caseName}</font><br>
${report.url}<br>
错误原因:${report.msg}<br>
<hr>
</#list>
</div>
<span>Sent using FreeMarker Template</span>
</body>
</html>
网友评论