我编写了一个java程序,其中我必须渲染ftl并在字符串变量中获取输出。 请在下面找到我的代码:
Configuration cfg = new Configuration();
StringWriter stringWriter = new StringWriter();
try
{
Template template = cfg.getTemplate("src/response.get.html.ftl");
model.put("content",contextModel);
template.process(model, stringWriter);
System.out.println(stringWriter);
}
但是我在 Template template = cfg.getTemplate("src/response.get.html.ftl");
中遇到文件未找到异常
我已将我的响应文件放在 src 中,并将我的 java 文件放在 com.test.webscripts 包中。根据http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/没关系。但我无法弄清楚为什么我会得到异常(exception)。有人可以帮我吗?
提前致谢!
最佳答案
通常 src
在运行时无法访问,因为它仅供编译器和其他构建工具使用。构建完成后,应用程序应该只依赖于构建的输出(“二进制文件”),即使在 IDE 中 src
仍然存在(与部署应用程序时不同)。
此外,您还没有显示您使用的TemplateLoader
。你可能应该这样做:
cfg.setClassForTemplateLoading(SomeClassInMyApp.class, "/");
然后:
cfg.getTemplate("response.get.html.ftl");
创建子目录(例如 com/mycompany/myapp/templates
)是一种更安全的做法,并将模板放在那里。在这种情况下,您需要这个:
cfg.setClassForTemplateLoading(SomeClassInMyApp.class, "/com/mycompany/myapp/templates");
请注意,cfg.getTemplate("response.get.html.ftl"
保持不变,因为您在此处指定相对于模板目录的路径。
关于java - 尝试获取 ftl 模板时未找到文件异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919342/