spring 未找到Freemarker模板

qcuzuvrc  于 2023-02-18  发布在  Spring
关注(0)|答案(5)|浏览(242)

我目前正在尝试让Freemarker使用Spring来处理我的应用程序。无论我怎么尝试,我总是找不到模板。我不确定我是否正确设置了配置,但它从来没有找到我的模板。以下是我的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。
我不知道是否有人知道我做错了什么。
谢谢你的帮助!

46qrfjad

46qrfjad1#

我刚刚遇到了同样的问题,最后,我决定使用下面的方法:

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);
kqlmhetl

kqlmhetl2#

首先,/WEB-INF/freemarker只能作为WebApplicationContext内部的路径;否则Spring会尝试将其解析为文件系统路径而不是servlet上下文路径。您在上面发布的摘录是否来自DispatcherServlet正在加载的上下文?
其次,您为什么直接使用configuration而不是Spring的ViewResolver
最后,IOException可以表示许多不同的含义,您可以发布一个完整的堆栈跟踪吗?

zc0qhyus

zc0qhyus3#

我认为您必须确保文件“testTemplate.ftl”位于文件夹“/WEB-INF/freemarker/”中

cgfeq70w

cgfeq70w4#

你也可以把它设置成

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

在您的情况下:

<property name="templateLoaderPath" value="classpath:/WEB-INF/freemarker/"/>
afdcj2ne

afdcj2ne5#

这对我很有效:

configuration.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), "/templates");

相关问题