Spring Freemarker配置,模板未找到。

5

我有一个使用Spring/JSF的Web应用程序,它依赖于一个使用Freemarker模板的模块。下面是我的集成步骤:

我将applicationContext-freemarker-module.xml导入到applicationContext.xml中。 我在applicationContext-freemarker-module.xml中添加了配置bean,如下所示。

 <bean id="freemarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
   <property name="templateLoaderPath" value="classpath*:/"/>
 </bean>

我把我的模板放到了freemarker模块的src/main/resources目录下。 我通过以下方式读取模板:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-freemarker-module.xml");

Configuration templateConfig = (Configuration) context.getBean("freemarkerConfiguration");

Template template = templateConfig.getTemplate("template.ftl");

现在我已经尝试了很多templateLoaderPath属性的值,但我总是得到“Template not found.”异常。

Freemarker模块的JAR文件如下:

template.ftl
applicationContext-freemarker-module.xml
com/.../ (classes)
META-INF

我应该把模板文件放在哪里,templateLoaderPath值应该设置为什么? 我不明白为什么找不到"template.ftl"。我已经尝试了很多小时来设置正确的值,包括各种路径配置,但都没有成功。

非常感谢您的帮助。


你尝试过 <property name="templateLoaderPath" value="classpath:/"/> 吗?如果 .ftl 文件在 jar 包的根目录下,这应该可以工作... - javanna
是的,我已经尝试过了,但仍然找不到 .ftl 文件。非常感谢您的回复。 - jiraiya
2个回答

11

请确保您拥有以下内容:

  1. 在您的 *-action servlet xml 文件中,FreeMarkerConfigurationFactoryBean 配置的"preferFileSystemAccess" 属性设置为 "false"

  2. <property name="templateLoaderPath" value="classpath*:/"/> 应该更改为 <property name="templateLoaderPath" value="classpath:/"/>

    在 freemarker 中,模板加载器会尝试匹配字符串 "classpath:",而不是 "classpath*:"

  3. 您已经将 JAR 文件放置在 WEB-INF/lib 文件夹下。

  4. 最后,您的模板文件位于 jar 文件的根目录下。


对我来说有点不同:我使用了 "classpath:templates",但在 Jetty 上无法正常工作,将其更改为 "classpath:templates/" 后就可以正常工作了! - dannrob
你好Jay,如果我的模板在依赖的jar包中,我该如何加载这些模板。我使用classpath*:/mailer_templates,但是它不起作用。 ) - Felix
@Felix:请检查上面提到的第二点。classpath 不应该有一个 *。 - Jay

3

使用类似以下的 bean:

<bean
    class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
    <property name="templateLoaderPath" value="classpath:META-INF/freemarker/" />
    <property name="preferFileSystemAccess" value="false" />
</bean>

希望这能帮到你。

这个配置在注解中的等效方式是什么? - Sue

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