Freemarker模板未找到。

4

我目前正在尝试使用Spring将Freemarker与我的应用程序配合使用。无论我尝试什么,都会出现“找不到模板”的错误。我不确定我的配置是否正确,但它从未找到我的模板。这是我的Spring bean配置:

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
</bean>

每当我尝试在freemaker配置中调用getTemplate时,它总是返回一个找不到模板的错误。所以如果我这样做:
configuration.getTemplate("testTemplate.ftl") 

这段代码总是抛出一个IOException异常。

我不确定是否有人知道我做错了什么。

感谢您的所有帮助!


你是如何设置“configuration”对象的? - tinkertime
我正在从Spring获取配置对象。FreeMarkerConfigurer中有一个getConfiguration方法。 - brock
5个回答

2

我刚遇到了同样的问题,最终我决定采用以下方法:

Configuration configuration = new Configuration();
FileTemplateLoader templateLoader = new FileTemplateLoader(new File(YOUR_BASE_TEMPLATE_DIR));
configuration.setTemplateLoader(templateLoader);
freemarker.template.Template template = configuration.getTemplate(YOUR_TEMPLATE_NAME);
template.process(datamodel, writer);

我尝试了,但对我没有用。我仍然收到异常java.io.FileNotFoundException,即使路径存在。这真的很疯狂! - Felipe

0
首先,/WEB-INF/freemarker 只能在 WebApplicationContext 内使用作为路径;否则 Spring 会尝试将其解析为文件系统路径而不是 servlet 上下文路径。您发布的摘录是否来自由 DispatcherServlet 加载的上下文?
第二,您直接使用 configuration 而不使用 Spring 的 ViewResolver 有什么原因吗?
最后,IOException 可能意味着许多不同的东西。您能发布完整的堆栈跟踪吗?

谢谢回复!我原本以为是路径问题...所以我正在尝试使用freemarker通过使用模板来帮助发送电子邮件。我最初认为ViewResolver有点过于繁琐了。所以我想使用配置会更好一些...不确定这是否正确。至于IOException,返回的消息是找不到模板。 - brock
哦,我正在applicationContext.xml文件中配置bean。我没有把它放在DispatchServlet中。 - brock
如何为“applicationContext.xml”创建上下文(使用哪个Spring类来创建它)?如果它不是从WebApplicationContext派生的,它将无法从“/WEB-INF”获取任何内容 - 除非您指定绝对文件系统URL。 - ChssPly76
谢谢ChssPly76。我正在使用Classpath应用程序上下文来加载我的applicationContext.xml。如何加载WebApplicationContext?在Web应用程序中使用它是正确的上下文吗? - brock
它通常由 DispatcherServlet(http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html#mvc-servlet)加载,但您也可以手动创建它(http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/GenericWebApplicationContext.html),并将 servlet 上下文传递给它。 - ChssPly76
嗨@Brock,你最终解决了问题吗?是什么解决了它? - JackDev

0

你也可以像这样设置

    @Bean
    public FreeMarkerConfigurationFactoryBean freemarkerConfiguration() {
        FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
        bean.setTemplateLoaderPath("classpath:/templates/");
        return bean;
    }

在你的情况下:
    <property name="templateLoaderPath" value="classpath:/WEB-INF/freemarker/"/>

0
这对我有用:
configuration.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), "/templates");

-1

我认为你必须确保文件“testTemplate.ftl”在文件夹“/WEB-INF/freemarker/”中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接