[JAVA] Repeated sample with Apache Freemarker

Nowadays, I had the opportunity to use Apache Free Marker. At that time, I couldn't find a Japanese sample that outputs Loop repeatedly in Map, so I will write a sample with a memo.

Premise

Apache FreeMarker:2.3.28

Output result

This time, HTML is output using FreeMarker. The output result is as shown in the figure below.

The Table tag and the value at the bottom of the Table are output by FreeMarker. result.png

pom.xml

  <dependencies>
    <!-- FreeMarker -->
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.28</version>
    </dependency>
  </dependencies>

template Save the template in [src / main / resource / template.html]. It is a setting to output the tr tag of the Table tag and the

tag under the Table tag by repeating List or Map.

<html>
  <span>[table from list]</span>
  <table style="border-collapse: collapse;" cellspacing="1" cellpadding="5">
    <tbody>
      <tr align="center">
        <td style="background-color:#edf5f9;border:1px solid #42B4ED;font-weight: bold;" width="25%">parameter</td>
        <td style="background-color:#edf5f9;border:1px solid #42B4ED;font-weight: bold;" width="18%">value</td>
        <td style="background-color:#edf5f9;border:1px solid #42B4ED;font-weight: bold;" width="57%">comment</td>
      </tr>
      
      <!-- Output rows from java.util.List -->
      <#list itemList as item>
      <tr>
        <td style="border: 1px solid #42B4ED;">${item.param}</td>
        <td style="border: 1px solid #42B4ED;">${item.value}</td>
        <td style="border: 1px solid #42B4ED;">${item.comment}</td>
      </tr>
      </#list>   
    </tbody>
  </table>
  
  <!-- Output a row from java.util.Map -->
  </br>
  <div>[value from map]</div>
  <#list mapValue as key, value>
  <div>
    <span>${key}:${value}</span>
  </div>
  </#list>
</html>

Java

The source code will be described for each part (process block).

Parameter for Template

The coding of the parameter (variable value) to be passed to FreeMarker is as follows.


    //====== Build template parameter ======//
    Map<String, Object> paramMap = new HashMap<>();
      
    // build itemList
    List<Map<String, String>> itemList = new ArrayList<>();
    Map<String, String> itemMap1 = new HashMap<>();
    itemMap1.put("param", "param1");
    itemMap1.put("value", "99.1");
    itemMap1.put("comment", "hogehoge");
    itemList.add(itemMap1);
    Map<String, String> itemMap2 = new HashMap<>();
    itemMap2.put("param", "param2");
    itemMap2.put("value", "98.2");
    itemMap2.put("comment", "hogehoge2");
    itemList.add(itemMap2);
    paramMap.put("itemList", itemList);
    
    // build mapValue
    Map<String, String> mapValue = new HashMap<>();
    mapValue.put("param3", "97.3");
    mapValue.put("param4", "96.4");
    paramMap.put("mapValue", mapValue);

Since it is difficult to understand the contents of Map if it is the source, I will also add the result of toString of [paramMap].

paramMap


{
  itemList=[
    {param=param1, value=99.1, comment=hogehoge}, 
    {param=param2, value=98.2, comment=hogehoge2}
  ],
  mapValue={
    param3=97.3, 
    param4=96.4
  }
}

Output

FreeMarker Template initialization and output processing is as follows. The output result is output to the standard output and file (result.html).

    //====== Initialize template ======//
    // New Config
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
    
    // Encoding
    cfg.setDefaultEncoding("UTF-8");

    // Set template path
    cfg.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), "/");
  
    //====== Output ======//
    try {

      // Get template
      Template template = cfg.getTemplate("template.html");
      
      // Write to system out
      Writer out = new OutputStreamWriter(System.out);
      template.process(paramMap, out);
      out.flush();
      
      // Write to file
      try (Writer fw = new FileWriter(new File("result.html"))) {
        template.process(paramMap, fw);
        out.flush();
      }
      
    } catch(IOException | TemplateException ex) {
      ex.printStackTrace();
      System.exit(1);
    }

Git

See GitHub for all source code

Recommended Posts

Repeated sample with Apache Freemarker
Apache FreeMarker memorandum
Apache beam sample code
Start Apache Solr with Embedded.
CSV output with Apache Commons CSV
Access Apache Kafka with Micronaut
Manipulate Excel with Apache POI
Circuit Breaker Pattern with Apache Camel
Download large files with Apache JMeter
Easy Pub/Sub messaging with Apache Kafka
EXCEL file update sample with JAVA
Restart apache with docker php-apache image
FileUpload with Rest on Apache Wicket
[Linux] Start Apache container with Docker