1 2 3 4

模版引擎

 

FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件配置文件源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
FreeMarker是免费的,基于Apache许可证2.0版本发布。其模板编写为FreeMarker Template Language(FTL),属于简单、专用的语言。需要准备数据在真实编程语言中来显示,比如数据库查询和业务运算, 之后模板显示已经准备好的数据。在模板中,主要用于如何展现数据, 而在模板之外注意于要展示什么数据。

 

 

//生成块jsp
for(CrfBlock block:page.getCrfBlocks()){
String blockName = "block"+block.getId();
blockName = blockName+ ".jsp";
freemark.setFileName(blockName);
freemark.setTemplateName("block.ftl");   //调用模版
t = null;
try {
t = freemark.getConfiguration().getTemplate(freemark.getTemplateName());
} catch (IOException e) {
e.printStackTrace();
}

outFile = new File(freemark.getFilePath()+ freemark.getFileName());  //输出文件
out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
fun.crfBlock(block, user, map, projectcrfservice);
try {
t.process(map, out);
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

 

 

 

package com.edc.util;
import java.io.File;
import java.io.IOException;
import freemarker.template.Configuration;

/**
* 使用freemark生成word
* @author stormwy
*
*/
public class Freemark {
/**
* freemark初始化
* @param templatePath 模板文件位置
* @throws IOException
*/
public Freemark(String templatePath) throws IOException {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(templatePath));
}
/**
* freemark模板配置
*/
private Configuration configuration;
public Configuration getConfiguration() {
return configuration;
}

public void setConfiguration(Configuration configuration) {
this.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;
}

}

posted @ 2017-03-24 10:33  一缕清风丶  阅读(22)  评论(0编辑  收藏  举报