Implement an automatic code generation: Template Engine Freemarker

Keywords: PHP FreeMarker Java xml JSP

Catalog

Preface

In current development, code generation is already an indispensable feature. Each company will have its own set of customized project skeleton, while modern code generation is automatic and template engine is indispensable, so in this blog, you will read about freemarker's role in code generation and its introductionShows how to use it in Java projects!

Template Engine FreeMarker

What is a template engine?

Template Engine refers to a technology that separates common code from business data. It has many implementations, such as substitution, explanatory, compiled, JSP is one of the widely used template engine technologies (it is essentially a Servlet to generate Html files).

What is FreeMarker?

Official documents:

FreeMarker is a template engine: a generic tool based on templates and data to be altered to generate output text (HTML web pages, e-mail, configuration files, source code, and so on).It's not for end users, it's a Java class library, a component that programmers can embed in the products they develop.
The template is written as FreeMarker Template Language (FTL).It is a simple, specialized language, not a mature programming language like PHP.That means preparing the data for display in a real programming language, such as database queries and business operations, and then the template displays the prepared data.In a template, you can focus on how the data is presented, while outside the template, you can focus on what data is being displayed.

Simply put, FreeMarker decomposes the target text into Model s, View s, and the engine itself acts as a Controller, a common MVC pattern.
FreeMarker uses a predefined template file (ftl file), populates attributes such as Java objects, and outputs the target file.

How does FreeMarker work?

Unlike JSP, FreeMarker requires a binding of Servlet s to use. In Java, all we need to do is import the corresponding Jar package!Next, you'll see how to use FreeMarker in your Maven project.

Join Dependency

First, let's add FreeMarker dependencies to pom.xml:

<dependency>   
    <groupId>org.freemarker</groupId>    
    <artifactId>freemarker</artifactId>    
    <version>2.3.23</version>
</dependency>

Create Configuration Instance

// step1 creates a freemarker.template.Configuration configuration instance
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);

Create a data model

We can use a String, or an instance of the following type, as the data model, using a custom Bean here.

Use java.lang.String to build strings.
Use java.lang.Number to derive numeric types.
Use java.lang.Boolean to construct Boolean values.
Use a java.util.List or Java array to build the sequence.
Use java.util.Map to build a hash table.
Use a custom bean class to build a hash table where the items in the bean correspond to the properties of the bean.For example, the product's price attribute (getProperty()) can be obtained through product.price.(Actions for beans are also available this way; see here for more information)

//Create a root hash object to load data objects
Map<String, Object> root = new HashMap<>();
//Loading data objects into hash
root.put("user", new User("Joe",17));

Custom User Classes Used

//User
public class User {  
    private String name;
    private int age;
    
    public String getName()
    {    
        return name;
    }
    public int getAge()
    {    
        return age;
    }
    
    User(String name, int age) {
    this.age = age;
    this.name = name;
    }
 }

Create a template file (.ftl file)

<--! demo.ftl -->
<user>
    <name>user.name</name>
    <age>user.age</age>
</user>

Get Templates

Get the demo.ftl template file we created earlier

Template temp = cfg.getTemplate("demo.ftl");

Merge Templates and Data

We know from the beginning of FreeMarker that Data Model + Template = Target Output, and in the end, we only need to bind the template we get to a custom root hash object, using the Template process() method here;

//Create output stream, define output file
File docFile = new File("demo.xml");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
//The process method binds the data to the template and outputs it to the out output stream
temp.process(root, out);

Finally, we successfully created a new demo.xml file!

<--! demo.ftl -->
<user>
    <name>Joe</name>
    <age>17</age>
</user>

Integrate code

// Create a freemarker.template.Configuration configuration instance
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
//Create a root hash object to load data objects
Map<String, Object> root = new HashMap<>();
//Loading data objects into hash
root.put("user", new User("Joe",17));
//Get Templates
Template temp = cfg.getTemplate("demo.ftl");
//Create output stream, define output file
File docFile = new File("demo.xml");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
//The process method binds the data to the template and outputs it to the out output stream
temp.process(root, out);

Posted by imstupid on Sun, 21 Jul 2019 09:41:25 -0700