FreeMarker(二)模板加载

FreeMarker(二)模板加载

  Freemarker使用freemarker.template.Configuration类进行模板加载,有3种设置模板存放路径的方法。分别是:

  (1)类路径

    public void setClassForTemplateLoading(Class resourceLoaderClass, String basePackagePath) {...}  

  (2)文件路径

    public void setClassLoaderForTemplateLoading(ClassLoader classLoader, String basePackagePath) {...}

  (3)Servlet上下文

    public void setServletContextForTemplateLoading(Object servletContext, String path) {...}

  

  在此之前可以点击此处了解绝对路径和相对路径的知识。

  Configuration config = new Configuration(new Version(2, 3, 22));//获取config对象,本人使用的版本是2.3.22

  一:类路径

  

  本例通过Test测试类获取testchild包下的template.html模板

  config.setClassForTemplateLoading(Test.class, "/testchild");//设置模板路径

  Template template = config.getTemplate("template.html");//获取模板

  二:文件路径

  获取项目template文件夹下的template.html模板

   config.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir")+"/template"));//设置模板路径

  Template template = config.getTemplate("template.html");//获取模板

  三:Servlet上下文-基于WebRoot下的模板文件

  本例获取WebRoot下template文件夹下的template.html模板文件。

  configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");//设置模板路径

  Template template = config.getTemplate("template.html");//获取模板

   

 

posted @ 2018-01-12 11:19  maxudong  阅读(589)  评论(0编辑  收藏  举报