You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring环境下无法读取FreeMarker模板文件,请求技术解决方案

Fixing "Could not read freemarker template" Issue

Let’s work through the key fixes to resolve your template loading problem:

1. Correct the Template Path in getTemplate()

Looking at your code, your FreeMarkerConfigurationFactoryBean sets the template loader path to classpath:/freemarker/, but when you call freemarkerConfiguration.getTemplate("/email_notification.txt"), you’re adding an extra leading slash. This makes FreeMarker look for classpath:/freemarker//email_notification.txt (double slash), which won’t resolve correctly.

Update the line to:

content.append(FreeMarkerTemplateUtils.processTemplateIntoString(
    freemarkerConfiguration.getTemplate("email_notification.txt"), model));

2. Verify File Location & Packaging

  • Double-check that email_notification.txt exists exactly at src/main/resources/freemarker/ (note: file names are case-sensitive on Linux/macOS, even if your dev machine uses Windows).
  • After building your project, open the generated JAR/WAR file and confirm the template is present under BOOT-INF/classes/freemarker/ (for Spring Boot) or the corresponding resources directory. If it’s missing, ensure src/main/resources is marked as a resources root in your IDE.

3. Enhance FreeMarker Configuration

Add default encoding to your configuration bean to avoid potential encoding-related loading issues, and ensure the bean initializes properly:

@Bean 
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() { 
    FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean(); 
    bean.setTemplateLoaderPath("classpath:/freemarker/");
    bean.setDefaultEncoding("UTF-8"); // Add this line to set consistent encoding
    return bean; 
}

4. Get Full Exception Context

Right now you’re only printing e.getMessage() in your catch block, which hides critical details about the failure. Update the catch block to print the full stack trace:

catch(Exception e){
    System.out.println("Exception occured while processing fmtemplate:");
    e.printStackTrace(); // This will show exactly why the template can't be read (e.g., file not found, permission issues)
}

Quick Note on Velocity’s Strikethrough Issue

If you’re curious, the strikethrough in Velocity was likely due to unescaped HTML or accidental use of syntax like ## comments that rendered as strikethrough, or variable references resolving to empty strings with unintended styling. But since you’ve switched to FreeMarker, focusing on the above fixes should get your template loading working.


内容的提问来源于stack exchange,提问作者Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:52:30