Implement an automatic code generation (a): template engine Freemarker

Foreword

In what is now in development, code generation is already an essential function, each company will have its own set of customized project framework, to achieve automatic code generation template engine is essential, so in this blog in freemarker will explain the role played in code generation, and how to use it in Java project!

FreeMarker template engine

What template engines?

Template engine generally refers to the common code and business data separate from the technology, which has a variety of implementations, such as replacement type, interpreted, compiled, such as JSP is one of the widely used technique of template engine (which is essentially a Servlet, for generating Html file)

What FreeMarker are?

The official document:

FreeMarker is a template engine: that is, a template-based and data to be changed, and used to generate output text (HTML web pages, e-mail, configuration files, source code, etc.) of common tools. It is not for end users, but a Java class library that programmers can embed a component of their product development.
Writing templates for FreeMarker Template Language (FTL). It is simple, specific language, like PHP is not as mature programming language. That means to prepare data to be displayed on a real programming language, such as database queries and business operations, after the template has been prepared to display data. In the template, you can focus on how to present the data, but outside of a template can focus on what you want to display data.

Simply put, the goal is to FreeMarker text broken down into Model, View, and then the engine itself acts as a Controller, which is common MVC pattern.
FreeMarker, then Java object as an attribute of the file by filling good template (FTL file) defined in advance, the final output object file.

FreeMarker How to use?

Unlike FreeMarker JSP, Servlet need to bind to use, in Java, we only need to import the corresponding Jar package is ready for use! Next will be introduced in the Maven project on how to use the FreeMarker.

Join dependence

First, let the pom.xml join rely FreeMarker in:

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

Creating Configuration Examples

// step1 创建freemarker.template.Configuration配置实例
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);

Creating a Data Model

We can use a String, instance or less act as a type of data model, used here in a Bean custom .

Java.lang.String used to construct a string.
Use java.lang.Number to derive digital type.
Use java.lang.Boolean to build a Boolean value.
Java.util.List or an array using Java to build sequence.
Java.util.Map use to build a hash table.
Using custom classes to build the hash table bean, bean and the bean property item corresponds. For example, product's price property (getProperty ()) can be obtained by product.price. (The action may get the bean this way; for more can see here)

//创建一个root hash对象,用来装载数据对象
Map<String, Object> root = new HashMap<>();
//将数据对象装载入hash中
root.put("user", new User("Joe",17));

Using the custom User class

//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 template

Before we get demo.ftl template file created

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

Merge templates and data

We know that in the beginning of understanding FreeMarker, data model + template = target output, in the end, we just need to get to the template, and from root hash object definitions to bind here will be to use the Template process () method ;

//创建输出流,定义输出的文件
File docFile = new File("demo.xml");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
//process方法将数据与模板进行绑定,输出到out输出流
temp.process(root, out);

Finally, we have successfully built a demo.xml file!

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

Integration Code

// 创建freemarker.template.Configuration配置实例
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
//创建一个root hash对象,用来装载数据对象
Map<String, Object> root = new HashMap<>();
//将数据对象装载入hash中
root.put("user", new User("Joe",17));
//获取模板
Template temp = cfg.getTemplate("demo.ftl");
//创建输出流,定义输出的文件
File docFile = new File("demo.xml");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
//process方法将数据与模板进行绑定,输出到out输出流
temp.process(root, out);

Guess you like

Origin www.cnblogs.com/joe2047/p/11223525.html