读书人

freemarker运用

发布时间: 2012-12-18 12:43:41 作者: rapoo

freemarker使用

public class ExportHtmlUtil {

?

private static Configuration cfg;

?

? ? static{

? ? ? ? cfg = new Configuration();

? ? }

/**

* 通过freemark生成html文件?

* @param rootPath ?文件生成后保存路径

* @param templetName ?模板名字 ?ftl 文件

* @param genFileName ?生成文件名字

* @param listLecture ?参数

* @return

*/

public static boolean genFileByFtl(String templetDir, String ?templetName ,String genFileName, List ?listParam ){

?

//取得工程classes的目录 作为ftl模板的目录

File dir = new File(ExportHtmlUtil.class.getClassLoader().getResource("/").getPath() );

?

Writer out = null;

try {

//加载模板存放目录

cfg.setDirectoryForTemplateLoading( dir );

//模板中传递参数

? ? ? ?Map<String, Object> root = new HashMap<String, Object>();

? ? ? ?root.put("listUser", listParam );

? ? ? ?

//Template t = cfg.getTemplate(ExportHtmlUtil.class.getClassLoader().getResource("/").getPath()+templetName );

Template t = cfg.getTemplate( templetName );

out = new OutputStreamWriter(new FileOutputStream( genFileName ), "UTF-8");

t.process(root, out);

out.flush();

out.close();

} catch ( Exception e) {

?e.printStackTrace();

?return false;

}finally{

try {

if(out!=null){

out.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

?

?

return true;

}

}

?

---------------------------

?

public String downloadHtml() ?{

FileInputStream fis = null;

OutputStream os =null;

try {

listLectureNote = lectureMng.getOneLecture(videoId,innerCwareID ,versionP );

List list = new ArrayList();

User user = new User();

user.setId(1);

user.setName("123");

user.setRealname("小王");

user.setAge(24);

String path = this.getRequest().getRealPath("/");

ExportHtmlUtil.genFileByFtl(path ,"entity.ftl" ?, path+File.separator+"user.html" , list);

HttpServletResponse response = this.getResponse();

response.setContentType("application/x-download");//设置为下载application/x-download

response.addHeader("Content-Disposition","attachment;filename=user.html");

fis = new FileInputStream(new File(path+File.separator+"user.html" ));

os = this.getResponse().getOutputStream() ;

byte[] bs = new byte[1024];

int len;

while( ? (len = fis.read(bs, 0, ?bs.length ))!=-1){

os.write(bs , 0, len);

}

os.flush();

os.close();

fis.close();

} catch ( Exception e) {

e.printStackTrace();

}finally{

try {

if(os!=null){

os.close();

}

if(fis!=null){

fis.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return null;

}

---------------------------------------------------

<#list listUser as user>

${r"<!--"} NodeText(${user.id!""},${user.name!""},${user.age!""}); ${r"-->"}

${user.realname!""}

${r"<!--"} NodeTextEnd();${r"-->"}

</#list>

读书人网 >编程

热点推荐