javaEE Freemarker模板引擎,页面静态化

Jar包下载:https://pan.baidu.com/s/1_kkZCyF-2Gm38jwg_E7t7g  密码:6tkl

FreeMarkerTest.java(测试类):

package cn.xxx.freemarker;

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

import org.junit.Test;

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

public class FreeMarkerTest {

	@Test
	public void testFreeMarker() throws Exception {
		//1、创建一个模板文件
		//2、创建一个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		//3、设置模板文件的目录
		configuration.setDirectoryForTemplateLoading(new File("D:/workspaces/MyWeb/WebContent/WEB-INF/ftl"));
		//4、设置模板文件的编码格式,一般就是utf-8
		configuration.setDefaultEncoding("utf-8");
		//5、加载一个模板文件,创建一个模板对象。
		Template template = configuration.getTemplate("hello.ftl");
		//6、创建一个数据集。可以是pojo也可以是map。推荐使用map
		Map data = new HashMap<>();
		data.put("hello", "hello freemarker!");  //会替换模板中的${hello}。类似EL表达式
		//7、创建一个Writer对象,指定输出文件的路径及文件名。
		Writer out = new FileWriter(new File("D:/freemarker/hello.txt"));
		//8、生成静态页面(文件)
		template.process(data, out);
		//9、关闭流
		out.close();
	}
}

WEB-INF/ftl/hello.ftl(模板文件,文件名和后缀名可以任意):

${hello}

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/83449778