Spring环境下无法读取FreeMarker模板文件,请求技术解决方案
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.txtexists exactly atsrc/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, ensuresrc/main/resourcesis 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

