Getting started with FreeMarker

1.1. What is freemarker

FreeMarker is a template engine written in Java language, which generates text output based on templates. FreeMarker has nothing to do with the Web container, that is, it doesn't know about servlets or HTTP when the Web is running. It can not only be used as the implementation technology of presentation layer, but also be used to generate XML, JSP or Java.

In current enterprises, Freemarker is mainly used for static page or page display

1.2. Usage of Freemarker

Add freemarker's jar package to the project.

Maven project add dependency



Use steps:

Step 1: create a Configuration object and directly new an object. The parameter of the constructor is the version number of freemarker.

Step 2: set the path of the template file.

Step 3: set the character set used by the template file. It's usually utf-8

Step 4: load a template and create a template object.

Step 5: create a dataset used by the template, which can be pojo or map. Generally map.

Step 6: create a Writer object, usually a FileWriter object, and specify the generated file name.

Step 7: call the process method of the template object to output the file.

Step 8: close the flow.



package fremark;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

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

 * @author: SHF
 * @date: 2018 11:16:05 am, March 20, 2010
 * @Description:freemark Test file
public class FremakeTest {
	public void freeMarkTest() throws IOException, TemplateException{
		//1. Create a template file hello.ftl
		//2. Create a Configuration object
		Configuration configuration=new Configuration(Configuration.getVersion());
		//3. Set the saving directory of template file
		configuration.setDirectoryForTemplateLoading(new File("E:/Eclipse/Graduation-Project/Graduation-Project/Graduation-item-web/src/main/webapp/WEB-INF/ftl"));
		//4. The coding mode of template file is generally utf-8
		//5. Load a template file and create a template object.
		Template template = configuration.getTemplate("hello.ftl");
		//6. Create a dataset, which can be pojo or map. Map is recommended
		Map map=new HashMap();
		map.put("hello", "hello shiye ,my first freeMarker");
		//7. Create a writer object, specify the path and filename of the output file
		Writer out=new FileWriter(new File("C:/Users/shiye/Desktop/hello.text"));
		//8. Generate static files
		template.process(map, out);
		//9. closing flow

Keywords: FreeMarker Java xml JSP

Added by ryanyoungsma on Sun, 05 Apr 2020 17:23:09 +0300