The first step, import dependence
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
Next, create a file named ftl expand the template
Four elements in the template file
1, the text, the direct output section
2, comments, i.e., <# --...--> not output format
3, interpolation (Interpolation): $ {..} That portion will be used in partial replacement data model output
4, FTL instructions: FreeMarker similar instructions, and HTML tags, plus # be distinguished former name, not output.
We will now create a simple template to create a file test.ftl
< HTML > < head > < Meta charset = "UTF-8" > < title > Freemarker entry of small DEMO </ title > </ head > < body > < # - I'm just a comment, I do not have any output - - > $ {name}, hello. Message {} $ </ body > </ HTML >
Here is the text, interpolation and comments
The third step is to generate a file
Steps for usage:
Step 1: Create a Configuration object, a new direct object. Freemarker argument constructor is the version number.
Step two: set the path template file is located.
The third step: character set template files. General is utf-8.
Step four: Load a template, create a template object.
Step 5: Create a data set to use a template, which can be pojo can also be a map. Usually Map.
Step Six: Create a Writer object, generally create a FileWriter object, specify the file name generation.
Step Seven: call the process method template object output file.
Eighth step: Close stream
Code:
Create a Test class main method is as follows:
// Create the configuration class 1
the Configuration the Configuration = new new the Configuration (Configuration.getVersion ());
// 2 where the template directory is set.
Configuration.setDirectoryForTemplateLoading (new new File ( "D: / demo_work / freemarkerDemo / src / main / Resources / "));
// 3 character set.
configuration.setDefaultEncoding (" UTF-8 ");
. 4 // load template
template template = configuration.getTemplate (" test.ftl ");
. // 5 to create a data model
Map = new new HashMap the Map ();
map.put ( "name", "Joe Smith");
map.put ( "the Message", "Welcome Freemarker!");
. 6 // create objects Writer
Writer out = new FileWriter ( File new new ( "D: \\ the test.html"));
// output. 7.
template.process (Map, OUT);
// close. 8 Writer object.
the out.close ();
After the execution, the D root directory to see test.html generated.