0

我很难让我的 SpringMVC 项目使用 FreeMarker。我发现这个类似的 SO 线程,但无法拼凑出实际的解决方案。我有一个“welcomeEmail.ftl”,我尝试同时放入资源/模板和 src/模板,但每次尝试运行它时都会出现错误:

java.io.FileNotFoundException: Template "welcomeEmail" not found.
    at freemarker.template.Configuration.getTemplate(Configuration.java:742)
    at freemarker.template.Configuration.getTemplate(Configuration.java:665)
    at com.xxx.utility.mail.FreemarkerFileTransformer.runTransformation(FreemarkerFileTransformer.java:44)

这是我的 JavaConfig:

 @Bean
    public FreeMarkerConfigurer freemarkerConfig() {
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
        freeMarkerConfigurer.setTemplateLoaderPath( "/templates" );
        return freeMarkerConfigurer;
    }


    @Bean
    public FreeMarkerViewResolver viewResolver() {
        FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
        freeMarkerViewResolver.setSuffix( ".ftl" );
        freeMarkerViewResolver.setPrefix( "" );
        freeMarkerViewResolver.setCache( true );
        return freeMarkerViewResolver;
    }

    @Bean
    public freemarker.template.Configuration configuration() {
        freemarker.template.Configuration configuration = new freemarker.template.Configuration();
        return configuration;
    }

我尝试这样使用 FreeMarker:

...  
private MailSender mailSender;
@Autowired
private FreemarkerFileTransformer freemarkerFileTransformer;


public void sendNewCustomerEmail(OfficeSetup officeSetup) throws Exception  {

    Map<String, String> m = new HashMap<String, String>();
    m.put("ownerName", officeSetup.getFirstName() + " " + officeSetup.getLastName());
    m.put("url", "weburl/" + officeSetup.getOfficeUrl());

    String mailContent = freemarkerFileTransformer.runTransformation(m, "", "welcomeEmail");

    SimpleMailMessage message = new SimpleMailMessage();

    message.setFrom("info@edelweissco.com");
    message.setTo(officeSetup.getUserName());
    message.setSubject("Welcome to eDentalManger, here are your activation details!");
    message.setText(mailContent);
    mailSender.send(message);

}


@Component
public class FreemarkerFileTransformer {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private Configuration configuration;

    public String runTransformation(Map<?, ?> sourceData, String ftlTemplate) throws Exception {

        Template template = configuration.getTemplate( ftlTemplate  );
        StringWriter writer = new StringWriter();
        template.process(sourceData, writer);
        writer.flush();
        String output = writer.getBuffer().toString();
        return output;
    }

由于我只将 FreeMarker 用于电子邮件,而且我没有 WEB-INF 目录,因此我不确定模板文件应该保存到哪里。

4

0 回答 0