Java template engine Freemarker2.x Advanced Guide

 

table of Contents

Foreword

Advanced Java template engine Freemarker2.x details

I, on the static page

Second, the static pages Features

Third, on the Freemarker

Four, Freemarker use steps

Five, Freemarker use

Six, Freemarker common grammar

Seven related documents


Foreword

In the project need to implement static pages, get a professional front-end personnel defined template, you can start slightly, why do you want to use Freemarker static framework, ah! This problem is not discussed here, the film blog introduces the Java template engine Freemarker2.x Advanced Guide.

Advanced Java template engine Freemarker2.x details

I, on the static page

What is a static Web page: Freemarker by some technical means or Thymeleaf dynamic pages JSP, asp.net, php, etc. are converted to static pages, access to ready-made static pages directly from the browser.

 

Second, the static pages Features

    1, accessed through a browser directly static pages, the program does not require treatment, high on its speed;
    2, good stability;
    3, more effectively prevent security vulnerabilities, such as less vulnerable to hacker attacks;
    4, static pages more easily indexed by search engines;

 

Third, on the Freemarker

FreeMarker is a Java language template engine, which is based on the template output text. FreeMarker has nothing to do with the Web container , that is in the Web, it does not know Servlet or HTTP. It not only can be used to achieve technical presentation layer, but also can be used to generate such as XML, JSP or Java.

FreeMarker Template Language (FTL). 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. This is often referred to as MVC (Model View Controller) mode, for a dynamic page, it is a particularly popular model.

FreeMarker design is actually being used to generate HTML pages, in particular based on the realization by the MVC (Model View Controller, Model - View - Controller) pattern Servlet applications. The idea of ​​using the MVC pattern of dynamic web pages so that you can front-end designer (written in HTML) separated from the programmers. All of their duties, to play its good side. Web designers can override the display page without being affected by programmers compiled code because the logic of the application (Java programs) and page design (FreeMarker templates) have been separated. Page template code will not be affected complex code. This separation of thought even for a page designer and programmer are the same person projects are very useful, because the separation makes the code be kept simple and easy to maintain.

Although FreeMarker also have programming skills, but it is not like that kind of a comprehensive PHP programming language. Instead, Java programs prepare the data to display (for example, SQL query), FreeMarker only use templates to generate pages that present text has been prepared data.

At present the enterprise is mainly used Freemarker do static pages or page impressions, so in this blog, bloggers are mainly used to do static Freemarker example.

 

Four, Freemarker use steps

    1) Create a Configuration object, a new direct object. Freemarker constructor parameter is the version number for the;
    2) set the path of the template file is located;
    3), character set template files. . 8 is a general-UTF;
    . 4), to load a template to create a template object;
    5), used to create a template of the data set, or may be may be pojo map. Generally the Map;
    . 6), to create a Writer object, creating a generally FileWriter object, the specified file name generation;
    7), the method calls the process output file template objects;
    8), close the stream;

 

Code examples are as follows:

package com.huazai.freemarker.test;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 通过模板技术实现静态网页的输出
 *              </ul>
 * @className TGenerateHtml
 * @package com.huazai.freemarker.test
 * @createdTime 2017年06月17日
 *
 * @version V1.0.0
 */
public class TGenerateHtml
{

	@Test
	public void GenHtml() throws Exception
	{
		// 1、创建个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		String diretoryp_ath = "模板文件所在的路径的目录";
		// 2、设置模板文件所在的路径的目录
		configuration.setDirectoryForTemplateLoading(new File(diretoryp_ath));
		// 3、设置模板文件的字符集
		configuration.setDefaultEncoding("UTF-8");
		// 4、首先创建模板文件,再加载模板文件 模板文件的后缀官方统一的标准是.ftl 其实任何类型都行。
		Template template = configuration.getTemplate("template.htm");// 可以是<相对路径>,也可以是<绝对路径>
		// 5、创建模板文件需要展示数据的数据集对象,可以使用POJO,也可以使用map 一般是使用map
		Map<String, String> model = new HashMap<>();
		model.put("hello", "hello");
		String pre_file_path = "生成的静态文件的文件路径";
		// 6、创建一个FileWriter对象 指定生成的静态文件的文件路径及文件名
		// 拼接一个前缀和后缀
		FileWriter writer = new FileWriter(new File(pre_file_path + "/result.html"));
		// 7、调用模板对象的process方法,执行输出文件。
		template.process(model, writer);
		// 8、关闭流
		writer.close();
	}
}

 

Five, Freemarker use

1), the new Maven project

2) introducing Maven dependency added freemarker project dependencies in pom.xml profile

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

3), a new data carrier EmployeeDTO

package com.huazai.freemarker.dto;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 员工实体
 *              </ul>
 * @className Employee
 * @package com.huazai.freemarker.pojo
 * @createdTime 2017年06月18日
 *
 * @version V1.0.0
 */
public class EmployeeDTO
{

	/**
	 * 员工ID
	 */
	private String empId;

	/**
	 * 员工姓名
	 */
	private String empName;

	public String getEmpId()
	{
		return empId;
	}

	public void setEmpId(String empId)
	{
		this.empId = empId;
	}

	public String getEmpName()
	{
		return empName;
	}

	public void setEmpName(String empName)
	{
		this.empName = empName;
	}

	@Override
	public String toString()
	{
		return "Employee [empId=" + empId + ", empName=" + empName + "]";
	}

	public EmployeeDTO()
	{
		super();
	}

	public EmployeeDTO(String empId, String empName)
	{
		super();
		this.empId = empId;
		this.empName = empName;
	}

}

 

Six, Freemarker common grammar

1), to achieve the output static pages by template technology <access key attribute in the Map>

package com.huazai.freemarker.test;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 通过模板技术实现静态网页的输出<访问Map中的key属性>
 *              <li>--访问Map中的key属性<br>
 *              <li>${hello}
 *              </ul>
 * @className TGenerateHtml
 * @package com.huazai.freemarker.test
 * @createdTime 2017年06月17日
 *
 * @version V1.0.0
 */
public class TKeyHtml
{

	@Test
	public void GenHtml() throws Exception
	{
		// 1、创建个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		String diretoryp_ath = "D:\\fremarker";
		// 2、设置模板文件所在的路径的目录
		configuration.setDirectoryForTemplateLoading(new File(diretoryp_ath));
		// 3、设置模板文件的字符集
		configuration.setDefaultEncoding("UTF-8");
		// 4、首先创建模板文件,再加载模板文件 模板文件的后缀官方统一的标准是.ftl 其实任何类型都行。
		Template template = configuration.getTemplate("template.ftl");// 可以是<相对路径>,也可以是<绝对路径>
		// 5、创建模板文件需要展示数据的数据集对象,可以使用POJO,也可以使用map 一般是使用map
		Map<String, String> model = new HashMap<>();
		model.put("hello", "hello world!");
		String pre_file_path = "D:\\fremarker";
		// 6、创建一个FileWriter对象 指定生成的静态文件的文件路径及文件名
		// 拼接一个前缀和后缀
		FileWriter writer = new FileWriter(new File(pre_file_path + "/result.html"));
		// 7、调用模板对象的process方法,执行输出文件。
		template.process(model, writer);
		// 8、关闭流
		writer.close();
	}
}

Template content:

--访问Map中的key属性<br>
${hello}

 

The effect is as follows:

 

2) to achieve output static pages by template technology <to access the POJO properties>

package com.huazai.freemarker.test;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.huazai.freemarker.dto.EmployeeDTO;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 通过模板技术实现静态网页的输出<访问POJO中的属性>
 * 				<li>-- 访问POJO中的属性<br>
 * 				<li>${employee.empId}
 * 				<li>${employee.empName}
 *              </ul>
 * @className TPojoHtml
 * @package com.huazai.freemarker.test
 * @createdTime 2017年06月17日
 *
 * @version V1.0.0
 */
public class TPojoHtml
{

	@Test
	public void GenHtml() throws Exception
	{
		// 1、创建个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		String diretoryp_ath = "D:\\fremarker";
		// 2、设置模板文件所在的路径的目录
		configuration.setDirectoryForTemplateLoading(new File(diretoryp_ath));
		// 3、设置模板文件的字符集
		configuration.setDefaultEncoding("UTF-8");
		// 4、首先创建模板文件,再加载模板文件 模板文件的后缀官方统一的标准是.ftl 其实任何类型都行。
		Template template = configuration.getTemplate("template.ftl");// 可以是<相对路径>,也可以是<绝对路径>
		// 5、创建模板文件需要展示数据的数据集对象,可以使用POJO,也可以使用map 一般是使用map
		Map<String, Object> model = new HashMap<>();
		model.put("employee", new EmployeeDTO("001", "huazai"));
		String pre_file_path = "D:\\fremarker";
		// 6、创建一个FileWriter对象 指定生成的静态文件的文件路径及文件名
		// 拼接一个前缀和后缀
		FileWriter writer = new FileWriter(new File(pre_file_path + "/result.html"));
		// 7、调用模板对象的process方法,执行输出文件。
		template.process(model, writer);
		// 8、关闭流
		writer.close();
	}
}

Template content:

-- 访问POJO中的属性<br>
${employee.empId}
${employee.empName}

 

The effect is as follows:

 

3), to achieve the output page template art static <accessing data set>

package com.huazai.freemarker.test;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.huazai.freemarker.dto.EmployeeDTO;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 通过模板技术实现静态网页的输出<访问集合中的数据>
 * 				<li>-- 访问集合中的数据<br>
 * 				<li><#list list as item>
 * 				<li>	${item_index}
 * 				<li>	${item.empId}
 * 				<li>	${item.empName}<br>
 * 				<li></#list>
 * 				<li>
 * 				<li>-- 逻辑判断语句<br>
 * 				<li><#list list as item>
 * 				<li>	<#if item_index%2==0>
 * 				<li>		这是偶数行》
 * 				<li>	<#else>
 * 				<li>		这是奇数行》
 * 				<li>	</#if>
 * 				<li>	${item_index}
 * 				<li>	${item.empId}
 * 				<li>	${item.empName}<br>
 * 				<li></#list>
 *              </ul>
 * @className TArrayHtml
 * @package com.huazai.freemarker.test
 * @createdTime 2017年06月17日
 *
 * @version V1.0.0
 */
public class TArrayHtml
{

	@Test
	public void GenHtml() throws Exception
	{
		// 1、创建个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		String diretoryp_ath = "D:\\fremarker";
		// 2、设置模板文件所在的路径的目录
		configuration.setDirectoryForTemplateLoading(new File(diretoryp_ath));
		// 3、设置模板文件的字符集
		configuration.setDefaultEncoding("UTF-8");
		// 4、首先创建模板文件,再加载模板文件 模板文件的后缀官方统一的标准是.ftl 其实任何类型都行。
		Template template = configuration.getTemplate("template.ftl");// 可以是<相对路径>,也可以是<绝对路径>
		// 5、创建模板文件需要展示数据的数据集对象,可以使用POJO,也可以使用map 一般是使用map
		Map<String, Object> model = new HashMap<>();
		List<EmployeeDTO> employeeDTOs = new ArrayList<EmployeeDTO>();
		employeeDTOs.add(new EmployeeDTO("1001", "冰心"));
		employeeDTOs.add(new EmployeeDTO("1002", "季羡林"));
		employeeDTOs.add(new EmployeeDTO("1003", "汪曾祺"));
		model.put("list", employeeDTOs);
		String pre_file_path = "D:\\fremarker";
		// 6、创建一个FileWriter对象 指定生成的静态文件的文件路径及文件名
		// 拼接一个前缀和后缀
		FileWriter writer = new FileWriter(new File(pre_file_path + "/result.html"));
		// 7、调用模板对象的process方法,执行输出文件。
		template.process(model, writer);
		// 8、关闭流
		writer.close();
	}
}

Template content:

-- 访问集合中的数据<br>
<#list list as item>
	${item_index}
	${item.empId}
	${item.empName}<br>
</#list>

 

The effect is as follows:

 

4), the output achieved by static page template technology <map data set access>

package com.huazai.freemarker.test;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.huazai.freemarker.dto.EmployeeDTO;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 通过模板技术实现静态网页的输出<访问map集合中的数据>
 * 				<li>-- 访问map集合中的数据<br>
 * 				<li><#list map?keys as key>
 * 				<li>	${map[key].empId}
 * 				<li>	${map[key].empName}<br>
 * 				<li></#list>
 *              </ul>
 * @className TMapHtml
 * @package com.huazai.freemarker.test
 * @createdTime 2017年06月17日
 *
 * @version V1.0.0
 */
public class TMapHtml
{

	@Test
	public void GenHtml() throws Exception
	{
		// 1、创建个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		String diretoryp_ath = "D:\\fremarker";
		// 2、设置模板文件所在的路径的目录
		configuration.setDirectoryForTemplateLoading(new File(diretoryp_ath));
		// 3、设置模板文件的字符集
		configuration.setDefaultEncoding("UTF-8");
		// 4、首先创建模板文件,再加载模板文件 模板文件的后缀官方统一的标准是.ftl 其实任何类型都行。
		Template template = configuration.getTemplate("template.ftl");// 可以是<相对路径>,也可以是<绝对路径>
		// 5、创建模板文件需要展示数据的数据集对象,可以使用POJO,也可以使用map 一般是使用map
		Map<String, Object> model = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		map.put("m1", new EmployeeDTO("1001", "冰心"));
		map.put("m2", new EmployeeDTO("1002", "季羡林"));
		map.put("m3", new EmployeeDTO("1003", "汪曾祺"));
		model.put("map", map);
		String pre_file_path = "D:\\fremarker";
		// 6、创建一个FileWriter对象 指定生成的静态文件的文件路径及文件名
		// 拼接一个前缀和后缀
		FileWriter writer = new FileWriter(new File(pre_file_path + "/result.html"));
		// 7、调用模板对象的process方法,执行输出文件。
		template.process(model, writer);
		// 8、关闭流
		writer.close();
	}
}

Template content:

-- 访问map集合中的数据<br>
<#list map?keys as key>
	${map[key].empId}
	${map[key].empName}<br>
</#list>

 

The effect is as follows:

 

5), to achieve the output by the static page template technology <formatted date type>

package com.huazai.freemarker.test;

import java.io.File;
import java.io.FileWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 通过模板技术实现静态网页的输出<日期类型格式化>
 * 				<li>-- 日期类型格式化<br>
 * 				<li>当前日期:${date?date}<br>
 * 				<li>当前时间:${date?time}<br>
 * 				<li>当前日期和时间:${date?datetime}<br>
 * 				<li>自定义日期格式:${date?string("yyyy年MM月dd日 HH时mm分ss秒")}<br>
 *              </ul>
 * @className TDateHtml
 * @package com.huazai.freemarker.test
 * @createdTime 2017年06月17日
 *
 * @version V1.0.0
 */
public class TDateHtml
{

	@Test
	public void GenHtml() throws Exception
	{
		// 1、创建个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		String diretoryp_ath = "D:\\fremarker";
		// 2、设置模板文件所在的路径的目录
		configuration.setDirectoryForTemplateLoading(new File(diretoryp_ath));
		// 3、设置模板文件的字符集
		configuration.setDefaultEncoding("UTF-8");
		// 4、首先创建模板文件,再加载模板文件 模板文件的后缀官方统一的标准是.ftl 其实任何类型都行。
		Template template = configuration.getTemplate("template.ftl");// 可以是<相对路径>,也可以是<绝对路径>
		// 5、创建模板文件需要展示数据的数据集对象,可以使用POJO,也可以使用map 一般是使用map
		Map<String, Object> model = new HashMap<>();
		model.put("date", new Date());
		String pre_file_path = "D:\\fremarker";
		// 6、创建一个FileWriter对象 指定生成的静态文件的文件路径及文件名
		// 拼接一个前缀和后缀
		FileWriter writer = new FileWriter(new File(pre_file_path + "/result.html"));
		// 7、调用模板对象的process方法,执行输出文件。
		template.process(model, writer);
		// 8、关闭流
		writer.close();
	}
}
	

Template content:

-- 日期类型格式化<br>
当前日期:${date?date}<br>
当前时间:${date?time}<br>
当前日期和时间:${date?datetime}<br>
自定义日期格式:${date?string("yyyy年MM月dd日 HH时mm分ss秒")}<br>

 

The effect is as follows:

 

6), to achieve static page template technique output <+ determined non-empty frame label>

package com.huazai.freemarker.test;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author HuaZai
 * @contact [email protected]
 *          <ul>
 * @description 通过模板技术实现静态网页的输出<非空判断 + 框架标签>
 * 				<li>-- 非空判断 + 框架标签<br>
 * 				<li>空值处理:${list!"这个是空值"}<br>
 * 				<li>引用页面01:<#include "page_01.htm"><br>
 * 				<li>引用页面02:<#include "page_02.htm"><br>
 * 				<li>引用页面03:<#include "page_03.htm"><br>
 *              </ul>
 * @className TRestHtml
 * @package com.huazai.freemarker.test
 * @createdTime 2017年06月17日
 *
 * @version V1.0.0
 */
public class TRestHtml
{

	@Test
	public void GenHtml() throws Exception
	{
		// 1、创建个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		String diretoryp_ath = "D:\\fremarker";
		// 2、设置模板文件所在的路径的目录
		configuration.setDirectoryForTemplateLoading(new File(diretoryp_ath));
		// 3、设置模板文件的字符集
		configuration.setDefaultEncoding("UTF-8");
		// 4、首先创建模板文件,再加载模板文件 模板文件的后缀官方统一的标准是.ftl 其实任何类型都行。
		Template template = configuration.getTemplate("template.ftl");// 可以是<相对路径>,也可以是<绝对路径>
		// 5、创建模板文件需要展示数据的数据集对象,可以使用POJO,也可以使用map 一般是使用map
		Map<String, Object> model = new HashMap<>();
		model.put("list", null);
		model.put("page_01_name", "这是01号页面");
		model.put("page_02_name", "这是02号页面");
		model.put("page_03_name", "这是03号页面");
		String pre_file_path = "D:\\fremarker";
		// 6、创建一个FileWriter对象 指定生成的静态文件的文件路径及文件名
		// 拼接一个前缀和后缀
		FileWriter writer = new FileWriter(new File(pre_file_path + "/result.html"));
		// 7、调用模板对象的process方法,执行输出文件。
		template.process(model, writer);
		// 8、关闭流
		writer.close();
	}
}

Template content:

-- 非空判断 + 框架标签<br>
空值处理:${list!"这个是空值"}<br>
引用页面01:<#include "page_01.ftl"><br>
引用页面02:<#include "page_02.ftl"><br>
引用页面03:<#include "page_03.ftl"><br>

 

The effect is as follows:

Involving multiple pages, this figure is omitted! ! !

 

 

 

Seven related documents

Freemarker Chinese version of the document: [ Freemarker Guide _ the Chinese version of the document ]

GitHub example source Address: [ Java template engine Freemarker2.x Advanced Guide ]


 Well, on Java template engine Freemarker2.x step guide to write here, and if you have any questions or encounter any questions please scan code to ask questions, you can give me a message oh, I will be 11 detailed answer. 
Twisters: "common learning and common progress," I hope you lot of attention CSND the IT community.


Author: Hua Tsai
Contact the author: [email protected]
Source: CSDN (Chinese Software Developer Network)
Original statement: https://blog.csdn.net/Hello_World_QWP/article/details/103805984
Copyright Notice: This article is a blogger original article, be sure to note the source text Myung-bak in the reprint!
发布了321 篇原创文章 · 获赞 651 · 访问量 149万+

Guess you like

Origin blog.csdn.net/Hello_World_QWP/article/details/103805984