A small problem with loading the template directory was encountered today using the Setclassfortemplateloading method of configuration in Freemarker.
Because of other forums on the Internet, blog writing a bit messy, so record.
Freemarker is a template frame, which is mainly to speed up the dye production. It has nothing to do with the Web container, as long as it is used to generate some code for the template.
such as the generation of Xml,java code. Other similar template frames also have velocity.
This article is mainly about the Freemarker loading template directory problem, its syntax is not described. The specific syntax can be downloaded from the official website reference Manual Reference.
Load Template Directory method
Freemarker provides 3 ways to load a template catalog. It uses the configuration class to load the template
The 3 ways are:
public void setclassfortemplateloading (Class clazz, String pathprefix);
public void setdirectoryfortemplateloading (File dir) throws IOException;
public void setservletcontextfortemplateloading (Object servletcontext, String path);
See the name also know, based on the class path, file system and servlet context.
Second, three kinds of nothing to say.
The second is based on the file system. For example, load the template file under/home/user/template.
Configuration cfg = new Configuration ();
Cfg.setdirectoryfortemplateloading (New File ("/home/user/template"));
Cfg.gettemplate ("BASE.FTL");
This will get the/HOME/USER/TEMPLATE/BASE.FTL template file.
The third type is web-based project. The second parameter is based on the Webroot.
For example: setservletcontextfortemplateloading (Context, "/FTL") is the/WEBROOT/FTL directory.
The first kind of method based on the classpath a little pit, in fact, look at the source code to know.
Like what:
Configuration cfg = new Configuration ();
Cfg.setclassfortemplateloading (Freemarkerutil.class, "/template");
Cfg.gettemplate ("BASE.FTL");
In fact, this method is based on the class load path to determine, and eventually execute the following code:
FreemarkerUtil.class.getClassLoader (). GetResource ("/template/");
Notice here. The second parameter needs to start with "/".
In fact, we look at the source will know: