FreeMarker start example

FreeMarker is a template engine: that is, a template-based and data to be changed, and used to produce 
general-purpose tool to output text (HTML web pages, e-mail, configuration files, source code, etc.) is. 

Works 
          Template (.ftl file freemarket syntax for writing based) + data model (java objects) = output (html, xml, java, jsp and other documents)

 

 

1. Create a project

2. Add dependence

 <dependencies>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

3. Create a template file

<! DOCTYPE HTML > 
< HTML lang = "EN" > 
< head > 
    < Meta charset = "UTF-. 8" > 
    < title > the Freemarker Test </ title >  </ head > 
< body > 
< # - this is freemarker Notes , not output to a file - > 

< h1 of > $ {name}; Message $ {} </ h1 of > 

</ body > 
</ HTML >

 

4. makefile

@Test
     public  void the Test () throws Exception { 

        // 1. create a Configuration object parameter is freemarker version number 
        Configuration the Configuration = new new Configuration (Configuration.getVersion ()); 

        // path 2. Set the template file is located in the 
        configuration. setClassForTemplateLoading (FreemarkerTest. class , "/ FTL" ); 

        // 3. character set file using 
        configuration.setDefaultEncoding ( "UTF-. 8" ); 

        // 4. Get template 
        template template = configuration.getTemplate ( "test. FTL " ); 

        // 5. the data set created using a template, may also be pojo Map; generally the Map 
        the Map <String, Object> = Mapnew new HashMap <> (); 
        map.put ( "name", "An Lili" ); 
        map.put ( "the Message", "the Hello Nice to Meet you!" ); 

        // 6. Create a Writer object, usually created FileWriter object, to specify a file name 
        FileWriter FileWriter = new new FileWriter ( "C: \\ the MyFiles Test \\ \\ \\ the Pomelo the test.html" ); 

        // 7. the process of calling the object method of the template file output 
        template.process ( Map, FileWriter); 

        // 8. The closed flow 
        fileWriter.close (); 


    }

 


Common notation 

    $ {} interpolation; only the output value, date or string, other types can not be output. 

    <#freemarker command 
    
    <# - comment -> 

    <@ use custom commands 

    ?? is to determine whether the object exists 

    ? function calls

 

Guess you like

Origin www.cnblogs.com/pomelo-lemon/p/11528856.html