FreeMarker quick start

FreeMarker quick start

FreeMarker is a template engine worth learning. It is a general tool for generating other text based on template files. This chapter provides a quick understanding of FreeMarker through how to use FreeMarker to generate Html # web pages and automatic code generation tools.

1 Introduction

FreeMarker is a template engine written in java language. Although it is not a web application framework, it is suitable to be a component of the web application framework.

characteristic:

1. Lightweight template engine, which can be easily embedded into the application without Servlet environment

2. Be able to generate various texts, such as html, xml, java, etc

3. It is easy to get started. It is written in java. Many grammars are similar to java

Working principle: (borrow online pictures)

2 FreeMarker program

Here you can experience the first FreeMarker program by simulating a simple code automatic production tool.

Project directory structure

Project creation process

Step 1: create a maven project and import the FreeMarker jar package

Step 2: create the directory templates and create a FreeMarker template file hello ftl

Step 3: create a freemarkerdemo that runs the FreeMarker template engine Java file

Step 4: refresh the project after running the main method

pom.xml file, maven project core file, management jar package.

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 3     <modelVersion>4.0.0</modelVersion>
 4     <groupId>com.freemark</groupId>
 5     <artifactId>freemarkerStudy</artifactId>
 6     <version>0.0.1-SNAPSHOT</version>
 7     <packaging>war</packaging>
 8 
 9     <dependencies>
10         <dependency>
11             <groupId>org.freemarker</groupId>
12             <artifactId>freemarker</artifactId>
13             <version>2.3.20</version>
14         </dependency>
15     </dependencies>
16     
17 </project>

hello. Basic syntax of FTL FreeMarker: ${xxx} xxx is equivalent to a placeholder. After the java background assigns a value to xxx, it is output through ${}

1 package ${classPath};
2 
3 public class ${className} {
4     
5     public static void main(String[] args) {
6         System.out.println("${helloWorld}");
7     }
8 
9 }

FreeMarkerDemo.java # core method, using FreeMarker # template engine.

 1 package com.freemark.hello;
 2 
 3 import java.io.BufferedWriter;
 4 import java.io.File;
 5 import java.io.FileOutputStream;
 6 import java.io.OutputStreamWriter;
 7 import java.io.Writer;
 8 import java.util.HashMap;
 9 import java.util.Map;
10 
11 import freemarker.template.Configuration;
12 import freemarker.template.Template;
13 
14 /**
15  * Most common questions: 
16  *     java.io.FileNotFoundException: xxx does not exist. Solution: be patient
17  *     FreeMarker jar The latest version (2.3.23) prompts that the Configuration method is deprecated
18  * Basic principle of automatic code production:
19  *     Data fill freeMarker placeholder
20  */
21 public class FreemarkerDemo {
22     
23     private static final String TEMPLATE_PATH = "src/main/java/com/freemark/hello/templates";
24     private static final String CLASS_PATH = "src/main/java/com/freemark/hello";
25     
26     public static void main(String[] args) {
27         // step1 establish freeMarker Configuration instance
28         Configuration configuration = new Configuration();
29         Writer out = null;
30         try {
31             // step2 Get template path
32             configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
33             // step3 Create data model
34             Map<String, Object> dataMap = new HashMap<String, Object>();
35             dataMap.put("classPath", "com.freemark.hello");
36             dataMap.put("className", "AutoCodeDemo");
37             dataMap.put("helloWorld", "Through simple <Code automatic production program> demonstration FreeMarker of HelloWorld!");
38             // step4 Load template file
39             Template template = configuration.getTemplate("hello.ftl");
40             // step5 Generate data
41             File docFile = new File(CLASS_PATH + "\\" + "AutoCodeDemo.java");
42             out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
43             // step6 output file
44             template.process(dataMap, out);
45             System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^AutoCodeDemo.java File created successfully !");
46         } catch (Exception e) {
47             e.printStackTrace();
48         } finally {
49             try {
50                 if (null != out) {
51                     out.flush();
52                 }
53             } catch (Exception e2) {
54                 e2.printStackTrace();
55             }
56         }
57     }
58 
59 }

After running the program and refreshing the project, you will find an additional autocodedemo java class. Not only java classes, but also xml. The author has made a simple tool class through FreeMarker, including a standard management page of the company and its functions of addition, deletion, modification and query, as well as relevant configuration files (13 files). All of them will be automatically generated after a carriage return (lazy ing).

3. FreeMarker syntax

The syntax is very similar to that of java, in which the concept of macro may be relatively unfamiliar. Start with the code first

stringFreeMarker. Main core knowledge points of ftl# FreeMarker

String output:
${"Hello ${name} !"} / ${"Hello " + name + " !"}
<#assign cname=r"Special characters complete output(http:\www.baidu.com)">
${cname}

String interception:
Obtain the letter corresponding to the subscript directly through the subscript: ${name[2]}
Starting subscript..End subscript intercept string: ${name
[0..5]}

Arithmetic operation:
<#--"+", "-", "", "/", "%" are supportedoperator -->
<#assign number1
= 10>
<#assign number2
= 5>
"+" : ${number1 + number2}
"-" : ${number1 - number2}
"" : ${number1 * number2}
"/" : ${number1 / number2}
"%" : ${number1 % number2}

Comparison operator:
<#if number1 + number2 gte 12 || number1 - number2 lt 6>
"*" : ${number1 * number2}
<#else>
"/" : ${number1 / number2}
</#if>

Built in function:
<#assign data = "abcd1234">
First capital: ${data?cap_first}
All letters are lowercase: ${data?lower_case}
All capital letters: ${data?upper_case}
<#assign floatData
= 12.34>
The value is taken as an integer: ${floatData?int}
Get the length of the collection: ${users?size}
Time format: ${dateTime?string(
"yyyy-MM-dd")}

Empty judgment and object collection:
<#if users??>
<#list users as user >
${user.id} - ${user.name}
</#list>
<#else>
${user!"If the variable is empty, a default value is given"}
</#if>

Map Set:
<#assign mapData={"name": "programmer", "salary":15000}>
Directly through Key obtain Value Value: ${mapData
["name"]}
adopt Key ergodic Map:
<#list mapData?keys as key>
Key: ${key} - Value: ${mapData
[key]}
</#list>
adopt Value ergodic Map:
<#list mapData?values as value>
Value: ${value}
</#list>

List Set:
<#assign listData=["ITDragon", "blog", "is", "cool"]>
<#list listData as value>${value} </#list>

include Instruction:
Import other files:<#include "otherFreeMarker.ftl" />

macro Macro instruction:
<#macro mo>
Define a macro without parameters macro--${name}
</#macro>
Using macros macro: <@mo />
<#macro moArgs a b c>
Define macros with parameters macro-- ${a+b+c}
</#macro>
Use macros with parameters macro: <@moArgs a=1 b=2 c=3 />

Namespace:
<#import "otherFreeMarker.ftl" as otherFtl>
${otherFtl.otherName}
<@otherFtl.addMethod a
=10 b=20 />
<#assign otherName
="modify otherFreeMarker.ftl Medium otherName Variable value"/>
${otherFtl.otherName}
<#assign otherName
="modify otherFreeMarker.ftl Medium otherName Variable value" in otherFtl />
${otherFtl.otherName}

otherFreeMarker.ftl FreeMarker file for testing namespace and include directives

other FreeMarker file
<#macro addMethod a b >
result : ${a + b}
</#macro>
<#assign otherName="Another one FreeMarker Variable of">

FreeMarkerDemo.java core method

 1 package com.freemark.demo;
 2 
 3 import java.util.List;
 4 import java.io.BufferedWriter;
 5 import java.io.File;
 6 import java.io.FileOutputStream;
 7 import java.io.OutputStreamWriter;
 8 import java.io.Writer;
 9 import java.util.Date;
10 import java.util.ArrayList;
11 import java.util.HashMap;
12 import java.util.Map;
13 
14 import freemarker.template.Configuration;
15 import freemarker.template.Template;
16 
17 public class FreeMarkerDemo {
18     
19     private static final String TEMPLATE_PATH = "src/main/java/com/freemark/demo/templates";
20     
21     public static void main(String[] args) {
22         // step1 establish freeMarker Configuration instance
23         Configuration configuration = new Configuration();
24         Writer out = null;
25         try {
26             // step2 Get template path
27             configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
28             // step3 Create data model
29             Map<String, Object> dataMap = new HashMap<String, Object>();
30             dataMap.put("name", "itdragon Blog");
31             dataMap.put("dateTime", new Date());
32             
33             List<User> users = new ArrayList<User>();
34             users.add(new User(1, "ITDragon Blog"));
35             users.add(new User(2, "welcome"));
36             users.add(new User(3, "You!"));
37             dataMap.put("users", users);
38             // step4 Load template file
39             Template template = configuration.getTemplate("stringFreeMarker.ftl");
40             // step5 Generate data
41             out = new OutputStreamWriter(System.out);
42             // step6 output file
43             template.process(dataMap, out);
44         } catch (Exception e) {
45             e.printStackTrace();
46         } finally {
47             try {
48                 if (null != out) {
49                     out.flush();
50                 }
51             } catch (Exception e2) {
52                 e2.printStackTrace();
53             }
54         }
55     }
56 
57 }

User.java to test FreeMarker's collection object

 1 package com.freemark.demo;
 2 
 3 public class User {
 4 
 5     private Integer id;
 6     private String name;
 7 
 8     public User() {
 9     }
10 
11     public User(Integer id, String name) {
12         this.id = id;
13         this.name = name;
14     }
15 
16     public Integer getId() {
17         return id;
18     }
19 
20     public void setId(Integer id) {
21         this.id = id;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31 
32     @Override
33     public String toString() {
34         return "User [id=" + id + ", name=" + name + "]";
35     }
36 
37 }

Final print results

String output:
Hello itdragon Blog ! / Hello itdragon Blog !
Special characters complete output(http:\www.baidu.com)

String interception:
Obtain the letter corresponding to the subscript directly through the subscript: d
Starting subscript..End subscript intercept string: itdrag

Arithmetic operation:
"+" : 15
"-" : 5
"*" : 50
"/" : 2
"%" : 0

Comparison operator:
"*" : 50

Built in function:
First capital: Abcd1234
All letters are lowercase: abcd1234
All capital letters: ABCD1234
Integer value: 12
Get the length of the collection:
3
Time format:
2017-10-29

Empty judgment and object collection:
1 - ITDragon Blog
2 - welcome
3 - You!

Map Set:
Directly through Key obtain Value Value: Programmer
adopt Key ergodic Map:
Key: name - Value: programmer
Key: salary
- Value: 15,000
adopt Value ergodic Map:
Value: programmer
Value:
15,000

List Set:
ITDragon blog is cool

include Instruction:
other FreeMarker file

macro Macro instruction:
Using macros macro: Define a macro without parameters macro--itdragon Blog
Use macros with parameters macro: Define macros with parameters macro
-- 6

Namespace:
Another one FreeMarker Variable of
result : 30
Another one FreeMarker Variable of
modify otherFreeMarker.ftl Medium otherName Variable value

Grammar explanation

data type

Unlike java, FreeMarker does not need to define the type of variable and can be assigned directly.

String: value = "xxxx". If there is a special character string = r"xxxx". Single quotation marks and double quotation marks are the same.

Value: value = 1.2. The value can be directly equal to, but the scientific counting method cannot be used.

Boolean: true or false.

List set: list = [1,2,3]; list=[1..100] indicates a set from 1 , to 100 , and vice versa.

Map set: Map = {"key": "value", "key2": "Value2"}, the key must be a string!

Entity class: similar to EL expression, click it directly.

String operation

String connection: you can directly nest ${"Hello, ${name}"}; You can also use the plus sign ${"Hello," + name}

String interception: string[index]. Index can be a value or a shape like 0 2 indicates that the subscript starts with 0 and ends with 2. There are three numbers altogether.

Comparison operator

==(equal to)= (not equal to), gt (greater than), gte (greater than or equal to), lt (less than), lte (less than or equal to). It is not recommended to use >, < may report an error!

It is generally used in combination with if

Built in function

FreeMarker # provides some built-in functions to convert the output. Its structure: variable? Built in function, so that the output variable can be converted through the built-in function.

1. html: HTML code the string;
2. cap_first: capitalize the first letter of the string;
3. lower_case: convert the string to lowercase;
4. upper_case: convert the string to uppercase;
5. size: get the number of elements in the set;
6. int: get the integer part of the number.

Variable null judgment

 ! Specify the default value of the missing variable; General configuration variable output usage
?? Judge whether the variable exists. Generally used in conjunction with if < #if value??? ></# if>

Macro instruction

It can be understood as the encapsulation method of java for use elsewhere. Macro instruction is also called custom instruction, macro instruction

The syntax is simple: < #macro Val > declare macro < / #macro >; Use macro < @ Val / >

Namespace

It can be understood as the import statement of java to avoid variable repetition. An important rule is that paths should not contain uppercase letters and should be underlined_ Separate words, myname -- > My_ name

The syntax is simple: < #import "XXX. FTL" as Val >

 

Other unspecified syntax is because, like java, there is nothing special. So it's not listed.

4 FreeMarker Web

This is integrated with spring MVC. I won't say much about the configuration of spring MVC. The author has also written relevant articles and will provide the source code at the same time

Import the relevant jar POM xml

<!-- freeMarker start -->
    <dependency>
         <groupId>org.freemarker</groupId>
         <artifactId>freemarker</artifactId>
         <version>2.3.20</version>
     </dependency>
     <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>4.1.4.RELEASE</version>
      </dependency>
  </dependencies> 
  <!-- freeMarker end -->

springmvc configuration file:

<!-- integration Freemarker -->
    <!-- Put on InternalResourceViewResolver In front of, give priority to freemarker -->  
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="/WEB-INF/views/templates"/>  
    </bean>  
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="prefix" value=""/>  
        <property name="suffix" value=".ftl"/>  
        <property name="contentType" value="text/html; charset=UTF-8"/>
    </bean>

Controller layer

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloFreeMarkerController {

@RequestMapping(</span>"/helloFreeMarker"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String helloFreeMarker(Model model) {
    model.addAttribute(</span>"name","ITDragon Blog"<span style="color: rgba(0, 0, 0, 1)">);  
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> "helloFreeMarker"<span style="color: rgba(0, 0, 0, 1)">;
}

}

Finally, the Freemarker file

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>FreeMarker Web</title>  
</head>  
<body>  
    <h1>Hello ${name} !</h1>  
</body>  
</html>

Source address: https://gitee.com/itdragon/springmvc

5 Summary

1. I know that FreeMarker is a template engine that can produce xml, html, java and other files

2. We know that FreeMarker files provide placeholders and java files provide data. We produce pages with data through FreeMarker template engine. In this paper, we put the data in Map. web applications can use setter/getter} methods

3. Know the display of strings, special characters and interception operation in FreeMarker syntax. And the use of some built-in methods

4. Focus on understanding FreeMarker's empty judgment knowledge points. Judge whether the variable is empty with "?", If the variable is empty, set the default value. If you don't pay attention to the blank problem, the prompt of yellow page may appear!

5. FreeMarker's macro concept, namespace, introduction of files, assignment of variables, traversal of sets, etc.

6. Freemarker integrates spring MVC.

 

Here, the introduction of FreeMarker is over. Isn't it very simple. If there is anything wrong, please correct it!

 

Extended links: Sort string sorting

 

Tags: FreeMarker

Posted by Trium918 on Wed, 11 May 2022 14:34:42 +0300