java framework - FreeMarker template engine

https://www.cnblogs.com/itdragon/p/7750903.html

FreeMarker is a very worthwhile to learn template engine. It is based on a common template file generation tool other text. By this chapter how to use FreeMarker to generate Html web pages and automatic code generation tools to quickly understand FreeMarker.

1 Introduction

FreeMarker is a language with java template engine, although it is not a web application framework, but it is very suitable as a component of a web application framework.

Features:

1. lightweight template engine, does not require Servlet environment can be easily embedded into applications

2 can generate a variety of texts, such as html, xml, java, etc.

3. Getting started is simple, it is written in java, java and many similar syntax

:( works borrowed from the pictures online)

2 FreeMarker program

Here FreeMarker to feel the first program code by simulating a simple automated production tool.

Project Directory Structure

Project Creation Process

Step 1: Create a maven project into FreeMarker jar package

Step 2: Create catalog templates, and create a FreeMarker template file hello.ftl

Step 3: Create a file to run FreeMarkerDemo.java FreeMarker template engine

Step 4: After running the main method Refresh Project

pom.xml file, maven project core files, manage jar package.

Copy the code
 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>
Copy the code

hello.ftl FreeMarker basic syntax: after} $ {xxx xxx as a placeholder, java xxx assigned to the background, and then output by $ {}

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

FreeMarkerDemo.java core methods, using FreeMarker template engine.

Copy the code
Package com.freemark.hello. 1; 
 2 
 . 3 Import java.io.BufferedWriter; 
 . 4 Import java.io.File; 
 . 5 Import java.io.FileOutputStream; 
 . 6 Import java.io.OutputStreamWriter; 
 . 7 Import a java.io.Writer; 
 . 8 the java.util.HashMap Import; 
 . 9 Import a java.util.Map; 
10 
. 11 Import freemarker.template.Configuration; 
12 is Import freemarker.template.Template; 
13 is 
14 / ** 
15 * the most common problem: 
16 * the java.io. FileNotFoundException: xxx does not exist solution: be patient 
17 * the latest version of FreeMarker jar (2.3.23) Tip Configuration method was abandoned 
18 * automatic production Code basic principle: 
19 * data filled freeMarker placeholders 
20 * /  
21 public class FreemarkerDemo {
twenty two     
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 创建freeMarker配置实例
28         Configuration configuration = new Configuration();
29         Writer out = null;
30         try {
31             // step2 获取模版路径
32             configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
33             // step3 创建数据模型
34             Map<String, Object> dataMap = new HashMap<String, Object>();
35             dataMap.put("classPath", "com.freemark.hello");
DataMap.put 36 ( "className", "AutoCodeDemo");
47             e.printStackTrace();
37 dataMap.put ( "helloWorld", "simple <automatic code production process> FreeMarker presentation of the HelloWorld!"); 
38 is loaded Step4 template file // 
39 = configuration.getTemplate Template Template ( "hello.ftl"); 
40 // step5 generating data 
41 is docfile = new new file file (CLASS_PATH + "\\" + "AutoCodeDemo.java"); 
42 is new new BufferedWriter, OUT = (the OutputStreamWriter new new (new new a FileOutputStream (docfile))); 
43 is the output file // Step6 
44 template.process (Datamap, OUT); 
45 System.out.println ( "^^^^^^^^^^^^^^^^^^^^^^^^ AutoCodeDemo.java file created successfully!") ;
46         } catch (Exception e) {
48         } finally {
49             try {
50                 if (null != out) {
51                     out.flush();
52                 }
53             } catch (Exception e2) {
54                 e2.printStackTrace();
55             }
56         }
57     }
58 
59 }
Copy the code

After running the program refreshes the project, you will find more than a AutoCodeDemo.java class. Just like java, xml also possible. The author is through FreeMarker made a simple tools, the company's management page and a standard CRUD functions, as well as associated configuration file (thirteen file), a carriage return will all automatically generated (lazy ing).

3 FreeMarker grammar

Java syntax is very similar, in which the concept of the macro may be unfamiliar, the first on the code

stringFreeMarker.ftl FreeMarker main core knowledge points

Copy the code
Output string: 
$ { "! The Hello $ {name}"} / {$ "!" "The Hello" + name +} 
<= R & lt #assign CNAME "output special character is completed (http: \ www.baidu.com)" > 
$ {} CNAME 

string interception: 
Get index is assigned directly via the subscript letter: $ {name [2]} 
starting end subscript index .. taken string: $ {name [0..5]} 

arithmetic calculation: 
<# - support "+", "-", "*", "/", "%" operator -> 
<#assign number1 = 10> 
<#assign number2. 5 => 
"+": $ number1 number2} + { 
"-": $ {number1 - number2} 
"*": $ {number1 number2} * 
"/": $ {number1 / number2} 
"%": $ {} number1% number2 

comparison operators: 
< GTE 12 is number1 + number2 #if number1 || - lt. 6 number2> 
"*" : ${number1 * number2}
<#else>
"/" : ${number1 / number2}
</#if>

内建函数:
<#assign data = "abcd1234"> 
first letter: {? data cap_first} $ 
all lowercase: $ {? data lower_case} 
all capital letters: Data UPPER_CASE $ {?} 
<#assign floatData = 12.34> 
values taken integer: $ {floatData int?} 
Get the length of the collection: $ {? users size} 
time format: $ {? dateTime string ( " yyyy-MM-dd")} 

blank determination and collection of objects: 
<#if Users ?? > 
<#list Users aS User> 
$ {} the user.id - the user.name $ {} 
</ # List> 
<#else> 
{! User "variable is empty a default value to" $} 
</ IF #> 

Map set: 
<#assign MapData = { "name": "programmers", "salary": 15000} > 
direct access by the value Key value: $ {mapData [ "name" ]} 
by traversing Key Map: 
<#list MapData ? AS Key Keys> 
Key:{Key} $ - Value: $ {MapData [Key]} 
</ # List> 
traversed by Map Value:
<#list mapData?values as value>
Value: ${value}
</ # List> 

List set: 
<#assign the listData = [ "ITDragon", "Blog", "IS", "Cool"]> 
<#list the listData AS value> $ {value} </ # List> 

the include instructions for: 
introduction of other documents: <# the include "otherFreeMarker.ftl" /> 

macro macro: 
<#macro Mo> 
defined macro no parameters macro - $ {name} 
</ # macro> 
using a macro macro: <@mo /> 
< #macro moArgs ab c> 
defined macro parameters {a + B $ macro-- + C} 
</ # macro> 
using parameterized macro macro: <@moArgs a = 1 b = 2 c = 3 /> 

namespace : 
<#import "otherFreeMarker.ftl" AS otherFtl> 
$} {otherFtl.otherName 
<otherFtl.addMethod @ 20 is A = B = 10 /> 
<#assign otherName = "modify otherFreeMarker.#assign otherName = "otherName modified otherFreeMarker.ftl the variable value" /> 
$ {} otherFtl.otherName
<#assign otherName = "otherName modified otherFreeMarker.ftl the variable value" in otherFtl /> 
$ {} otherFtl.otherName
Copy the code

otherFreeMarker.ftl To test the namespace and include instructions FreeMarker file

Other documents FreeMarker 
<ab & #macro the addMethod> 
Result: $ {A + B} 
</ Macro #> 
<#assign otherName = "Another variable FreeMarker">

FreeMarkerDemo.java core methods

Copy the code
 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 创建freeMarker配置实例
23         Configuration configuration = new Configuration();
24         Writer out = null;
25         try {
26             // step2 获取模版路径
27             configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
28             // step3 创建数据模型
29             Map<String, Object> dataMap = new HashMap<String, Object>();
30             dataMap.put("name", "itdragon博客");
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 (the User new new (2, "Welcome"));
36             users.add(new User(3, "You!"));
37             dataMap.put("users", users);
38             // step4 加载模版文件
39             Template template = configuration.getTemplate("stringFreeMarker.ftl");
40             // step5 生成数据
41             out = new OutputStreamWriter(System.out);
42             // step6 输出文件
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}
Copy the code

To test the User.java FreeMarker collection object

Copy the code
 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 }
Copy the code

最后的打印结果

Copy the code
字符串输出:
Hello itdragon博客 ! / Hello itdragon博客 !
特殊字符完成输出(http:\www.baidu.com)

字符串截取 : 
通过下标直接获取下标对应的字母: d
起点下标..结尾下标截取字符串:itdrag

算数运算:
"+" : 15
"-" : 5
"*" : 50
"/" : 2
"%" : 0

比较运算符:
"*" : 50

内建函数:
第一个字母大写:Abcd1234
所有字母小写:abcd1234
所有字母大写:ABCD1234
数值取整数:12
获取集合的长度:3
时间格式化:2017-10-29

空判断和对象集合:
1 - ITDragon 博客
2 - 欢迎
3 - You!

Map集合:
直接通过Key获取 Value值:程序员
通过Key遍历Map:
Key: name - Value: 程序员
Key: salary - Value: 15,000
通过Value遍历Map:
Value: 程序员
Value: 15,000

List集合:
ITDragon blog is cool 

include指令:
其他FreeMarker文件

macro宏指令:
使用宏macro: 定义无参数的宏macro--itdragon博客
使用带参数的宏macro: 定义带参数的宏macro-- 6

命名空间:
另外一个FreeMarker的变量
result : 30
另外一个FreeMarker的变量
修改otherFreeMarker.ftl中的otherName变量值
Copy the code

语法详解

数据类型

和java不同,FreeMarker不需要定义变量的类型,直接赋值即可。

字符串: value = "xxxx" 。如果有特殊字符 string = r"xxxx" 。单引号和双引号是一样的。

数值:value = 1.2。数值可以直接等于,但是不能用科学计数法。

布尔值:true or  false。

List集合:list = [1,2,3] ; list=[1..100] 表示 1 到 100 的集合,反之亦然。

Map集合:map = {"key" : "value" , "key2" : "value2"},key 必须是字符串哦!

实体类:和EL表达式差不多,直接点出来。

字符串操作

字符串连接:可以直接嵌套${"hello , ${name}"} ; 也可以用加号${"hello , " + name}

字符串截取:string[index]。index 可以是一个值,也可以是形如 0..2 表示下标从0开始,到下标为2结束。一共是三个数。

比较运算符

== (等于),!= (不等于),gt(大于),gte(大于或者等于),lt(小于),lte(小于或者等于)。不建议用 >,<  可能会报错!

一般和 if 配合使用

内建函数

FreeMarker 提供了一些内建函数来转换输出,其结构:变量?内建函数,这样就可以通过内建函数来转换输出变量。

1. html: 对字符串进行HTML编码;
2. cap_first: 使字符串第一个字母大写;
3. lower_case: 将字符串转成小写;
4. upper_case: 将字符串转成大写;
5. size: 获得集合中元素的个数;
6. int: 取得数字的整数部分。

变量空判断

 !    指定缺失变量的默认值;一般配置变量输出使用
??    判断变量是否存在。一般配合if使用 <#if value??></#if>

宏指令

可以理解为java的封装方法,供其他地方使用。宏指令也称为自定义指令,macro指令

语法很简单:<#macro val > 声明macro </#macro>; 使用macro <@val />  

命名空间

可以理解为java的import语句,为避免变量重复。一个重要的规则就是:路径不应该包含大写字母,使用下划线_分隔词语,myName --> my_name

语法很简单:<#import "xxx.ftl" as val> 

 

其他没有说明的语法是因为和java一样,没什么特别之处。所以没有列出来。

4 FreeMarker Web

这里是和SpringMVC整合的,SpringMVC的配置就不多说了,笔者也写过相关的文章,同时也会提供源码

导入相关的jar pom.xml

Copy the code
<!-- 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 -->
Copy the code

springmvc的配置文件:

Copy the code
<!-- 整合Freemarker -->
    <!-- 放在InternalResourceViewResolver的前面,优先找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>
Copy the code

Controller 层

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

@Controller
public class HelloFreeMarkerController {
    
    @RequestMapping("/helloFreeMarker")
    public String helloFreeMarker(Model model) {
        model.addAttribute("name","ITDragon博客");  
        return "helloFreeMarker";
    }

}
Copy the code

最后是Freemarker文件

Copy the code
<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>
Copy the code

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

5 Summary

1. Know FreeMarker is a template engine that can produce xml, html, java and other documents

2. Know FreeMarker file provides a placeholder, java file provides data, there is a page of data by FreeMarker template engine production, the text data is placed into a Map. web application can use setter / getter method

3. Know the special character string FreeMarker syntax, operations taken. And some use the built-in method

4. focus on understanding the empty judge's knowledge FreeMarker. Variable is determined whether the air with "??", if the variable is null set defaults. If you pay attention to air issues that may prompt the yellow pages of Oh!

5. FreeMarker macro concept of namespaces, import documents, assign values ​​to variables, traversal collection.

6. Freemarker integration SpringMVC.

 

Getting here FreeMarker's over, is not very simple. If there is something wrong, please correct me!

Guess you like

Origin www.cnblogs.com/hmit/p/11608241.html