无法读取 freemarker 模板
Posted
技术标签:
【中文标题】无法读取 freemarker 模板【英文标题】:Could not read freemarker template 【发布时间】:2018-06-28 13:04:54 【问题描述】:我的文件在 src/main/resources/freemarker/email_notification.txt
我无法读取包含 html 文件的 freemaker 文件,即 email_notification.txt。
我的参考来自这里:http://websystique.com/spring/spring-4-email-using-velocity-freemaker-template-library/
我试过velocity法,但是有些字有删除线,所以我选择freemarker法。
@Transactional
@Service("EmailService")
public class EmailService
@Autowired
JavaMailSender mailSender;
@Autowired
Configuration freemarkerConfiguration;
public void sendEmail(Map<String, Object> params)
MimeMessagePreparator preparator = getMessagePreparator(params);
try
mailSender.send(preparator);
System.out.println("Message has been sent.............................");
catch (MailException ex)
System.err.println(ex.getMessage());
private MimeMessagePreparator getMessagePreparator(final Map<String, Object> params)
MimeMessagePreparator preparator = new MimeMessagePreparator()
public void prepare(MimeMessage mimeMessage) throws Exception
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject(params.get("trnmaster").toString());
helper.setFrom("XXXXX@gmail.com");
helper.setTo("XXXXXX@hotmail.com");
String text = geFreeMarkerTemplateContent(params);//Use Freemarker or Velocity
System.out.println("Template content : "+text);
helper.setText(text, true);
;
return preparator;
public String geFreeMarkerTemplateContent(Map<String, Object> model)
StringBuffer content = new StringBuffer();
try
content.append(FreeMarkerTemplateUtils.processTemplateIntoString(
freemarkerConfiguration.getTemplate("/email_notification.txt"),model));
return content.toString();
catch(Exception e)
System.out.println("Exception occured while processing fmtemplate:"+e.getMessage());
return "";
部分配置文件
@Bean
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration()
FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
bean.setTemplateLoaderPath("classpath:/freemarker/");
return bean;
【问题讨论】:
【参考方案1】:在你配置 FreeMarker 的地方,你应该使用:bean.setTemplateLoaderPath("classpath:/freemarker/");
这个例子也很奇怪。为什么文件扩展名是txt
?对于 HTML 模板,它应该是 ftlh
(在旧项目中是 ftl
)。另外我肯定会覆盖FreeMarkerConfigurationFactoryBean.postProcessConfiguration
并根据https://freemarker.apache.org/docs/pgui_quickstart_createconfiguration.html 进行推荐的设置,除了你不能调用setDirectoryForTemplateLoading
,而且可能setDefaultEncoding
也已经被Spring 设置好了。确保您获得自动 HTML 转义非常重要(incompatibleImprovements
设置为 2.3.24 或更高版本,ftlh
文件扩展名可以做到这一点)。
【讨论】:
以上是关于无法读取 freemarker 模板的主要内容,如果未能解决你的问题,请参考以下文章
使用FreeMarker生成数据,模板明明没错却一直报错“The following has evaluated to null or missing:”