简体   繁体   English

找不到Freemarker模板

[英]Freemarker template not found

I'm currently trying to get Freemarker to work with my application using Spring. 我目前正在尝试让Freemarker使用Spring使用我的应用程序。 No matter what I try I keep getting template not found. 无论我尝试什么,我都会不断找不到模板。 I am not sure if I have the configuration set up properly, but it never finds my template. 我不确定是否正确设置了配置,但是它永远找不到我的模板。 Here is my spring bean config: 这是我的Spring bean配置:

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

Whenever I try to call getTemplate on the freemaker configuration it always sends back a template not found error. 每当我尝试在freemaker配置上调用getTemplate时,它总是会发回模板未找到错误。 So if I do 所以如果我这样做

configuration.getTemplate("testTemplate.ftl") 

it always throws an IOException. 它总是抛出IOException。

I'm not sure if anyone has an idea of what I'm doing wrong. 我不确定是否有人知道我在做什么错。

Thanks for all your help! 感谢你的帮助!

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

First of all, /WEB-INF/freemarker would only work as a path from within WebApplicationContext ; 首先, /WEB-INF/freemarker只能作为WebApplicationContext内部的路径; otherwise Spring would attempt to resolve it as file system path rather than servlet context path. 否则,Spring将尝试将其解析为文件系统路径而不是servlet上下文路径。 Is the excerpt you've posted above from the context being loaded by DispatcherServlet ? 您上面发布的摘录是否是由DispatcherServlet加载的上下文?

Secondly, is there any reason why are you using configuration directly instead of using Spring's ViewResolver ? 其次,是否有任何原因为什么您直接使用configuration而不是使用Spring的ViewResolver

Finally, IOException can mean many different things. 最后, IOException可能意味着很多不同的东西。 Can you post a full stack trace? 您可以发布完整的堆栈跟踪信息吗?

you can also set it like 您也可以将其设置为

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

In your case: 在您的情况下:

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

I've just had the same kind of problem and, at the end, I decide to use the approach below: 我遇到了同样的问题,最后,我决定使用以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM