模板引擎freemarker的简单使用教程

本文介绍如何使用Freemarker模板引擎生成Word文档。通过创建模板、设置模板参数及使用Java程序填充数据,最终生成带有特定信息的Word文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

freemarker十分强大,而且不依赖web容器,个人感觉十分好用。

下面直接进主题,freemarker还有什么特性,请找度娘或谷哥~


一、freemarker生成word

1.创建模板。
我创建模板的方法比较简单,也不知道有没有其他更好的方法,有的话,请告诉我吧~
首先是新建一个word文档,按照内容格式排好版,然后在需要注入信息的位置先写上占位置的数据,如图1,然后另存为xml文件(我是存为2003版本的xml),
然后用文本编辑器把xml打开,在xml中把对应的数据改为freemarker的输出表达式,如图2,然后保存,把xml的后缀名改为freemarker的文件后缀名ftl,便是一个freemarker模板了。


图1
2

2.实现程序
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

/**
 * 使用freemark生成word
 *
 */
public class Freemark {
	
	public static void main(String[] args){
		Freemark freemark = new Freemark("template/");
		freemark.setTemplateName("wordTemplate.ftl");
		freemark.setFileName("doc_"+new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date())+".doc");
		freemark.setFilePath("bin\\doc\\");
		//生成word
		freemark.createWord();
	}
	
	private void createWord(){
		
		Template t = null;
		try {
			//获取模板信息
			t = configuration.getTemplate(templateName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		File outFile = new File(filePath+fileName);
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		Map map = new HashMap<String, Object>();
		map.put("name", "蒙奇·D·路飞");
		map.put("country", "日本");
		map.put("city", "东京");
		map.put("time",new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date()));
		try {
			//输出数据到模板中,生成文件。
			t.process(map, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * freemark初始化
	 * @param templatePath 模板文件位置
	 */
	public Freemark(String templatePath) {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		configuration.setClassForTemplateLoading(this.getClass(),templatePath);		
	}	
	/**
	 * freemark模板配置
	 */
	private Configuration configuration;
	/**
	 * freemark模板的名字
	 */
	private String templateName;
	/**
	 * 生成文件名
	 */
	private String fileName;
	/**
	 * 生成文件路径
	 */
	private String filePath;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}
	
}


3.程序运行后,会在bin的doc目录下生成doc文件,效果图
4.demo源码下载:http://download.youkuaiyun.com/detail/stormwy/7370997

   因为Demo比较小,也可以通过图包的方式下载,把下图下载改名解压即可:



### 使用FreeMarker模板引擎进行Java开发 #### 配置环境 为了使用FreeMarker,在项目中需引入依赖库。对于Maven项目,可以在`pom.xml`文件中加入如下配置: ```xml <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> ``` #### 初始化Configuration对象 创建并初始化`Configuration`实例来设置模板路径和其他参数。 ```java import freemarker.template.Configuration; import freemarker.template.Template; public class TemplateEngine { private Configuration cfg; public TemplateEngine() throws Exception { // 创建一个新的配置实例 cfg = new Configuration(Configuration.VERSION_2_3_30); // 设置模板加载器,默认从类路径下读取模板文件 cfg.setClassForTemplateLoading(this.getClass(), "/templates/"); cfg.setDefaultEncoding("UTF-8"); cfg.setLocale(Locale.US); cfg.setOutputFormat(HtmlMarkupOutputFormat.INSTANCE); } } ``` #### 加载模板与数据模型处理 通过`cfg.getTemplate()`方法获取指定名称的模板,并准备要传递给模板的数据模型。 ```java Map<String, Object> dataModel = Maps.newHashMap(); dataModel.put("title", "Hello World!"); dataModel.put("message", "Welcome to FreeMarker!"); // 获取名为 'index.html' 的模板 Template temp = cfg.getTemplate("index.html"); Writer out = new OutputStreamWriter(System.out); try { // 将数据渲染到输出流 temp.process(dataModel, out); } finally { out.flush(); } ``` 当访问不存在变量或null值时,FreeMarker会将其视为错误终止执行[^3]。因此建议开发者在编写模板前充分考虑这些情况,可以利用内置函数如`${variable!default_value}`为可能为空的对象提供默认显示内容。 #### 处理HTML资源位置约定优于配置原则 按照惯例而非配置的方式工作意味着框架能够自动识别位于特定目录下的`.html`文档作为视图页面而无需额外设定。例如,如果定义了常量`DEFAULT_PREFIX="classpath:/templates/"` 和 `DEFAULT_SUFFIX=".html"` ,那么只需编辑resources/templates 文件夹内的 HTML 文件即可让Thymeleaf 自动呈现它们[^2]。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值