入门级freemarker的使用

本人是首次使用freemarker,这篇文章主要介绍freemarker的用处、安装、使用

1.用处

摘自百度:

FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。


其实说白了,freemarker就是一个模板引擎,也就是如果在项目中如果有想用模板的地,那么用它就可以了,比如现在你想生成一个学生证(PDF),格式固定好了,姓名、班级、学号是变量,那么你只需写出一个模板,在程序中直接调用模板赋值就可以了。


2.安装

所提到的东西

①jar包,需要freemarker-2.3.6.jar

②freemarker在eclipse中的编辑器(可以不用)


3.使用

下面是一个最简单的例子

①先创建模板文件

创建.ftl文件,然后输入一下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<th>学生证</th>
<tr><td>姓名:</td><td>${name}</td></tr>
<tr><td>班级:</td><td>${class}</td></tr>
<tr><td>学号:</td><td>${stuNo}</td></tr>
</table>
</body>
</html>

其中,$是插值符号,需要后台通过map赋值


②创建java程序,获取模板,配置文件路径,生成文件

package freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

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

public class NewFile {
	
	public static void main(String[] args) {
		NewFile newFile=new NewFile();
		try {
			Template tempplate=newFile.getConfiguration().getTemplate("student.ftl");
			//创建模板生成文件
			tempplate.process(newFile.getData(),newFile.createFile());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		
		
	}
	/**
	 * 获取ftl配置
	 * @return
	 */
	public Configuration getConfiguration(){
		File file=new File(".\\WebRoot\\");//存放.flt文件的位置,一定要是个目录
		Configuration config=  new Configuration();
		try {///读取文件,放在配置对象中
			config.setDirectoryForTemplateLoading(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		config.setObjectWrapper(new DefaultObjectWrapper());
		config.setDefaultEncoding("UTF-8");  
		return config;
	}
	/**
	 * 获取map
	 * @return
	 */
	public Map getData(){
		Map map = new HashMap();
		map.put("name", "李强");
		map.put("class", "金融081");
		map.put("stuNo","0806020127");
		return map;
	}

	
	public Writer createFile() throws IOException{
		File file = new File(".\\WebRoot\\doc\\student.txt");
		if(file.exists()){
			file.delete();
		}
		Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); 
		return writer;
	}

}

其中包括获取Configration,获取往模板中传入的map,获取生成的文件部分,通过运行主方法,就可以生成一个由模板生产的txt文件了。

其实我是想生成一个html来着,为了简单做个例子先做成这样。

freemarker还包括FTL指令,如 list,下个例子会讲解


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值