本人是首次使用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,下个例子会讲解