Freemarker提供了3种加载模板目录的方法。 它使用Configuration类加载模板。
三种方法分别是:
public void setClassForTemplateLoading(Class clazz, String pathPrefix);
public void setDirectoryForTemplateLoading(File dir) throws IOException;
public void setServletContextForTemplateLoading(Object servletContext, String path);
第一种:基于类路径,HttpWeb包下的framemaker.ftl文件
configuration.setClassForTemplateLoading(this.getClass(), "/HttpWeb");
configuration.getTemplate("framemaker.ftl"); //framemaker.ftl为要装载的模板
第二种:基于文件系统
configuration.setDirectoryForTemplateLoading(new File("/template"))
configuration.getTemplate("framemaker.ftl"); //framemaker.ftl为要装载的模板
第三种:基于Servlet Context,指的是基于WebRoot下的template下的framemaker.ftl文件
HttpServletRequest request = ServletActionContext.getRequest();
configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
configuration.getTemplate("framemaker.ftl"); //framemaker.ftl为要装载的模板
特别注意:tomcat启动和jar包启动加载的位置不同!
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
/** 加载模板 **/
//这个方法在eclipse跑是OK 的 打jar包部署获取不到模版
/*File file = ResourceUtils.getFile("classpath:templates");
configuration.setDirectoryForTemplateLoading(file);*/
// 这个方法在eclipse跑和打jar包部署都可以获取到模版
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
Template template = configuration.getTemplate("研判报告上报模板.ftl");