Maven集成FreeMarker遇未处理异常问题求助
Maven + FreeMarker 未处理异常问题解决
1. 核心问题:检查型异常未处理
FreeMarker的核心操作(加载模板、生成输出)会抛出IOException和TemplateException这类检查型异常,Java要求必须显式处理——要么用try-catch包裹,要么在方法上声明throws。
修正后的测试代码
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class FreemarkerTest { public static void main(String[] args) { Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); try { // 模板文件所在classpath路径,根据实际项目结构调整 cfg.setClassForTemplateLoading(FreemarkerTest.class, "/templates"); cfg.setDefaultEncoding("UTF-8"); // 加载指定模板文件(确保文件存在、拼写正确) Template template = cfg.getTemplate("test.ftl"); // 准备模板渲染所需数据 Map<String, Object> dataModel = new HashMap<>(); dataModel.put("title", "Maven集成FreeMarker测试"); dataModel.put("content", "模板渲染成功示例"); // 生成输出文件,用try-with-resources自动关闭流避免资源泄漏 try (FileWriter writer = new FileWriter("target/output.html")) { template.process(dataModel, writer); System.out.println("输出文件生成成功"); } } catch (IOException | TemplateException e) { // 捕获并处理异常,可根据业务需求替换为自定义告警或日志逻辑 e.printStackTrace(); } } }
2. 确认pom.xml依赖有效性
确保FreeMarker依赖配置正确,使用稳定兼容版本:
<dependencies> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.32</version> </dependency> </dependencies>
3. 额外排查点
- 模板路径:确认
/templates目录在项目src/main/resources或src/test/resources下,模板文件名无拼写错误 - 输出权限:生成文件的目标路径需确保当前运行用户有写入权限
- 变量匹配:模板中使用的变量名要和Java代码里
dataModel的key完全一致
内容的提问来源于stack exchange,提问作者Dany DRGH
相关产品推荐
相关产品推荐

